file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
2_29
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
3,778
/** * Rotates ijk coordinates 60 degrees clockwise. * */
block_comment
nl
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates<SUF>*/ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
2_34
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees counter-clockwise. */ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
3,778
/** * Rotates ijk coordinates 60 degrees counter-clockwise. */
block_comment
nl
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * * This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Mutable IJK hexagon coordinates * * Each axis is spaced 120 degrees apart. * * References two Vec2d cartesian coordinate systems: * * 1. gnomonic: face-centered polyhedral gnomonic projection space with * traditional scaling and x-axes aligned with the face Class II * i-axes. * * 2. hex2d: local face-centered coordinate system scaled a specific H3 grid * resolution unit length and with x-axes aligned with the local * i-axes */ final class CoordIJK { /** CoordIJK unit vectors corresponding to the 7 H3 digits. */ private static final int[][] UNIT_VECS = { { 0, 0, 0 }, // direction 0 { 0, 0, 1 }, // direction 1 { 0, 1, 0 }, // direction 2 { 0, 1, 1 }, // direction 3 { 1, 0, 0 }, // direction 4 { 1, 0, 1 }, // direction 5 { 1, 1, 0 } // direction 6 }; /** H3 digit representing ijk+ axes direction. * Values will be within the lowest 3 bits of an integer. */ public enum Direction { CENTER_DIGIT(0), K_AXES_DIGIT(1), J_AXES_DIGIT(2), JK_AXES_DIGIT(J_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), I_AXES_DIGIT(4), IK_AXES_DIGIT(I_AXES_DIGIT.digit() | K_AXES_DIGIT.digit()), IJ_AXES_DIGIT(I_AXES_DIGIT.digit() | J_AXES_DIGIT.digit()), INVALID_DIGIT(7), NUM_DIGITS(INVALID_DIGIT.digit()), PENTAGON_SKIPPED_DIGIT(K_AXES_DIGIT.digit()); Direction(int digit) { this.digit = digit; } private final int digit; public int digit() { return digit; } } int i; // i component int j; // j component int k; // k component CoordIJK(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Reset the value of the IJK coordinates to the provided ones. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ void reset(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } /** * Find the center point in 2D cartesian coordinates of a hex. */ public Vec2d ijkToHex2d() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return new Vec2d(i - 0.5 * j, j * Constants.M_SQRT3_2); } /** * Find the center point in spherical coordinates of a hex on a particular icosahedral face. */ public LatLng ijkToGeo(int face, int res, boolean substrate) { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); return Vec2d.hex2dToGeo(i - 0.5 * j, j * Constants.M_SQRT3_2, face, res, substrate); } /** * Add ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkAdd(int i, int j, int k) { this.i = Math.addExact(this.i, i); this.j = Math.addExact(this.j, j); this.k = Math.addExact(this.k, k); } /** * Subtract ijk coordinates. * * @param i the i coordinate * @param j the j coordinate * @param k the k coordinate */ public void ijkSub(int i, int j, int k) { this.i = Math.subtractExact(this.i, i); this.j = Math.subtractExact(this.j, j); this.k = Math.subtractExact(this.k, k); } /** * Normalizes ijk coordinates by setting the ijk coordinates * to the smallest possible positive values. */ public void ijkNormalize() { final int min = Math.min(i, Math.min(j, k)); ijkSub(min, min, min); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 counter-clockwise resolution. */ public void downAp7() { // res r unit vectors in res r+1 // iVec (3, 0, 1) // jVec (1, 3, 0) // kVec (0, 1, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 7 clockwise resolution. */ public void downAp7r() { // iVec (3, 1, 0) // jVec (0, 3, 1) // kVec (1, 0, 3) final int i = Math.addExact(Math.multiplyExact(this.i, 3), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 3), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 3), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 counter-clockwise resolution. */ public void downAp3() { // res r unit vectors in res r+1 // iVec (2, 0, 1) // jVec (1, 2, 0) // kVec (0, 1, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.j); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.k); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.i); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex centered on the current * hex at the next finer aperture 3 clockwise resolution. */ public void downAp3r() { // res r unit vectors in res r+1 // iVec (2, 1, 0) // jVec (0, 2, 1) // kVec (1, 0, 2) final int i = Math.addExact(Math.multiplyExact(this.i, 2), this.k); final int j = Math.addExact(Math.multiplyExact(this.j, 2), this.i); final int k = Math.addExact(Math.multiplyExact(this.k, 2), this.j); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates 60 degrees clockwise. * */ public void ijkRotate60cw() { // unit vector rotations // iVec (1, 0, 1) // jVec (1, 1, 0) // kVec (0, 1, 1) final int i = Math.addExact(this.i, this.j); final int j = Math.addExact(this.j, this.k); final int k = Math.addExact(this.i, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Rotates ijk coordinates<SUF>*/ public void ijkRotate60ccw() { // unit vector rotations // iVec (1, 1, 0) // jVec (0, 1, 1) // kVec (1, 0, 1) final int i = Math.addExact(this.i, this.k); final int j = Math.addExact(this.i, this.j); final int k = Math.addExact(this.j, this.k); this.i = i; this.j = j; this.k = k; ijkNormalize(); } /** * Find the normalized ijk coordinates of the hex in the specified digit * direction from the current ijk coordinates. * @param digit The digit direction from the original ijk coordinates. */ public void neighbor(int digit) { if (digit > Direction.CENTER_DIGIT.digit() && digit < Direction.NUM_DIGITS.digit()) { ijkAdd(UNIT_VECS[digit][0], UNIT_VECS[digit][1], UNIT_VECS[digit][2]); ijkNormalize(); } } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * clockwise aperture 7 grid. */ public void upAp7r() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.addExact(Math.multiplyExact(2, i), j)) / 7.0); this.j = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Find the normalized ijk coordinates of the indexing parent of a cell in a * counter-clockwise aperture 7 grid. * */ public void upAp7() { final int i = Math.subtractExact(this.i, this.k); final int j = Math.subtractExact(this.j, this.k); this.i = (int) Math.round((Math.subtractExact(Math.multiplyExact(3, i), j)) / 7.0); this.j = (int) Math.round((Math.addExact(Math.multiplyExact(2, j), i)) / 7.0); this.k = 0; ijkNormalize(); } /** * Determines the H3 digit corresponding to a unit vector in ijk coordinates. * * @return The H3 digit (0-6) corresponding to the ijk unit vector, or * INVALID_DIGIT on failure. */ public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; } /** * Rotates indexing digit 60 degrees clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60cw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.K_AXES_DIGIT.digit(); default -> digit; }; } /** * Rotates indexing digit 60 degrees counter-clockwise. Returns result. * * @param digit Indexing digit (between 1 and 6 inclusive) */ public static int rotate60ccw(int digit) { return switch (digit) { case 1 -> // K_AXES_DIGIT Direction.IK_AXES_DIGIT.digit(); case 5 -> // IK_AXES_DIGIT Direction.I_AXES_DIGIT.digit(); case 4 -> // I_AXES_DIGIT Direction.IJ_AXES_DIGIT.digit(); case 6 -> // IJ_AXES_DIGIT Direction.J_AXES_DIGIT.digit(); case 2 -> // J_AXES_DIGIT: Direction.JK_AXES_DIGIT.digit(); case 3 -> // JK_AXES_DIGIT: Direction.K_AXES_DIGIT.digit(); default -> digit; }; } }
28_45
/* * Copyright 2014 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.internal.tcnative.Buffer; import io.netty.internal.tcnative.Library; import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSLContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.NativeLibraryLoader; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static io.netty.handler.ssl.SslUtils.*; /** * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public final class OpenSsl { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class); private static final Throwable UNAVAILABILITY_CAUSE; static final List<String> DEFAULT_CIPHERS; static final Set<String> AVAILABLE_CIPHER_SUITES; private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES; private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES; private static final boolean SUPPORTS_KEYMANAGER_FACTORY; private static final boolean USE_KEYMANAGER_FACTORY; private static final boolean SUPPORTS_OCSP; private static final boolean TLSV13_SUPPORTED; private static final boolean IS_BORINGSSL; private static final Set<String> CLIENT_DEFAULT_PROTOCOLS; private static final Set<String> SERVER_DEFAULT_PROTOCOLS; static final Set<String> SUPPORTED_PROTOCOLS_SET; static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS; static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; static final String[] NAMED_GROUPS; static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED; // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL. // See https://github.com/netty/netty-tcnative/issues/567 // See https://www.java.com/en/configure_crypto.html for ordering private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" }; static { Throwable cause = null; if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) { cause = new UnsupportedOperationException( "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true"); logger.debug( "netty-tcnative explicit disabled; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause); } else { // Test if netty-tcnative is in the classpath first. try { Class.forName("io.netty.internal.tcnative.SSLContext", false, PlatformDependent.getClassLoader(OpenSsl.class)); } catch (ClassNotFoundException t) { cause = t; logger.debug( "netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable."); } // If in the classpath, try to load the native library and initialize netty-tcnative. if (cause == null) { try { // The JNI library was not already loaded. Load it now. loadTcNative(); } catch (Throwable t) { cause = t; logger.debug( "Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " + "application has already loaded the symbols by some other means. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } try { String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null); if (engine == null) { logger.debug("Initialize netty-tcnative using engine: 'default'"); } else { logger.debug("Initialize netty-tcnative using engine: '{}'", engine); } initializeTcNative(engine); // The library was initialized successfully. If loading the library failed above, // reset the cause now since it appears that the library was loaded by some other // means. cause = null; } catch (Throwable t) { if (cause == null) { cause = t; } logger.debug( "Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } } } UNAVAILABILITY_CAUSE = cause; CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols"); SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols"); if (cause == null) { logger.debug("netty-tcnative using native library: {}", SSL.versionString()); final List<String> defaultCiphers = new ArrayList<String>(); final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128); boolean supportsKeyManagerFactory = false; boolean useKeyManagerFactory = false; boolean tlsv13Supported = false; String[] namedGroups = DEFAULT_NAMED_GROUPS; String[] defaultConvertedNamedGroups = new String[namedGroups.length]; for (int i = 0; i < namedGroups.length; i++) { defaultConvertedNamedGroups[i] = GroupsConverter.toOpenSsl(namedGroups[i]); } IS_BORINGSSL = "BoringSSL".equals(versionString()); if (IS_BORINGSSL) { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" , "TLS_CHACHA20_POLY1305_SHA256" }; StringBuilder ciphersBuilder = new StringBuilder(128); for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) { ciphersBuilder.append(cipher).append(":"); } ciphersBuilder.setLength(ciphersBuilder.length() - 1); EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString(); } else { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; } try { final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER); long certBio = 0; long keyBio = 0; long cert = 0; long key = 0; try { // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually // handle TLSv13 as otherwise we may see runtime exceptions if (SslProvider.isTlsv13Supported(SslProvider.JDK)) { try { StringBuilder tlsv13Ciphers = new StringBuilder(); for (String cipher : TLSV13_CIPHERS) { String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL); if (converted != null) { tlsv13Ciphers.append(converted).append(':'); } } if (tlsv13Ciphers.length() == 0) { tlsv13Supported = false; } else { tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1); SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true); tlsv13Supported = true; } } catch (Exception ignore) { tlsv13Supported = false; } } SSLContext.setCipherSuite(sslCtx, "ALL", false); final long ssl = SSL.newSSL(sslCtx, true); try { for (String c: SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) || // Filter out TLSv1.3 ciphers if not supported. !tlsv13Supported && isTLSv13Cipher(c)) { continue; } availableOpenSslCipherSuites.add(c); } if (IS_BORINGSSL) { // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these // are supported. Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); Collections.addAll(availableOpenSslCipherSuites, "AEAD-AES128-GCM-SHA256", "AEAD-AES256-GCM-SHA384", "AEAD-CHACHA20-POLY1305-SHA256"); } PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII)); try { // Let's check if we can set a callback, which may not work if the used OpenSSL version // is to old. SSLContext.setCertificateCallback(sslCtx, null); X509Certificate certificate = selfSignedCertificate(); certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate); cert = SSL.parseX509Chain(certBio); keyBio = ReferenceCountedOpenSslContext.toBIO( UnpooledByteBufAllocator.DEFAULT, privateKey.retain()); key = SSL.parsePrivateKey(keyBio, null); SSL.setKeyMaterial(ssl, cert, key); supportsKeyManagerFactory = true; try { boolean propertySet = SystemPropertyUtil.contains( "io.netty.handler.ssl.openssl.useKeyManagerFactory"); if (!IS_BORINGSSL) { useKeyManagerFactory = SystemPropertyUtil.getBoolean( "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and so will be ignored in the future"); } } else { useKeyManagerFactory = true; if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and will be ignored when using BoringSSL"); } } } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } } catch (Error ignore) { logger.debug("KeyManagerFactory not supported."); } finally { privateKey.release(); } } finally { SSL.freeSSL(ssl); if (certBio != 0) { SSL.freeBIO(certBio); } if (keyBio != 0) { SSL.freeBIO(keyBio); } if (cert != 0) { SSL.freeX509Chain(cert); } if (key != 0) { SSL.freePrivateKey(key); } } String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null); if (groups != null) { String[] nGroups = groups.split(","); Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> unsupportedNamedGroups = new LinkedHashSet<String>(); for (String namedGroup : nGroups) { String converted = GroupsConverter.toOpenSsl(namedGroup); if (SSLContext.setCurvesList(sslCtx, converted)) { supportedConvertedNamedGroups.add(converted); supportedNamedGroups.add(namedGroup); } else { unsupportedNamedGroups.add(namedGroup); } } if (supportedNamedGroups.isEmpty()) { namedGroups = defaultConvertedNamedGroups; logger.info("All configured namedGroups are not supported: {}. Use default: {}.", Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)), Arrays.toString(DEFAULT_NAMED_GROUPS)); } else { String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); if (unsupportedNamedGroups.isEmpty()) { logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ", Arrays.toString(groupArray)); } else { logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ", Arrays.toString(groupArray), Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS))); } namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); } } else { namedGroups = defaultConvertedNamedGroups; } } finally { SSLContext.free(sslCtx); } } catch (Exception e) { logger.warn("Failed to get the list of available OpenSSL cipher suites.", e); } NAMED_GROUPS = namedGroups; AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites); final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2); for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) { // Included converted but also openssl cipher name if (!isTLSv13Cipher(cipher)) { availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS")); availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL")); } else { // TLSv1.3 ciphers have the correct format. availableJavaCipherSuites.add(cipher); } } addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES); addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES); // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL. addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites); DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers); AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites); final Set<String> availableCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size()); availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES); availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES); AVAILABLE_CIPHER_SUITES = availableCipherSuites; SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory; USE_KEYMANAGER_FACTORY = useKeyManagerFactory; Set<String> protocols = new LinkedHashSet<String>(6); // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled protocols.add(SslProtocols.SSL_v2_HELLO); if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) { protocols.add(SslProtocols.SSL_v2); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) { protocols.add(SslProtocols.SSL_v3); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) { protocols.add(SslProtocols.TLS_v1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) { protocols.add(SslProtocols.TLS_v1_1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) { protocols.add(SslProtocols.TLS_v1_2); } // This is only supported by java8u272 and later. if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) { protocols.add(SslProtocols.TLS_v1_3); TLSV13_SUPPORTED = true; } else { TLSV13_SUPPORTED = false; } SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols); SUPPORTS_OCSP = doesSupportOcsp(); if (logger.isDebugEnabled()) { logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET); logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS); } // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560. boolean javaxCertificateCreationSupported; try { javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)); javaxCertificateCreationSupported = true; } catch (javax.security.cert.CertificateException ex) { javaxCertificateCreationSupported = false; } JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported; } else { DEFAULT_CIPHERS = Collections.emptyList(); AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_CIPHER_SUITES = Collections.emptySet(); SUPPORTS_KEYMANAGER_FACTORY = false; USE_KEYMANAGER_FACTORY = false; SUPPORTED_PROTOCOLS_SET = Collections.emptySet(); SUPPORTS_OCSP = false; TLSV13_SUPPORTED = false; IS_BORINGSSL = false; EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; NAMED_GROUPS = DEFAULT_NAMED_GROUPS; JAVAX_CERTIFICATE_CREATION_SUPPORTED = false; } } static String checkTls13Ciphers(InternalLogger logger, String ciphers) { if (IS_BORINGSSL && !ciphers.isEmpty()) { assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0; Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length); Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); boolean ciphersNotMatch = false; for (String cipher: ciphers.split(":")) { if (boringsslTlsv13Ciphers.isEmpty()) { ciphersNotMatch = true; break; } if (!boringsslTlsv13Ciphers.remove(cipher) && !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) { ciphersNotMatch = true; break; } } // Also check if there are ciphers left. ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty(); if (ciphersNotMatch) { if (logger.isInfoEnabled()) { StringBuilder javaCiphers = new StringBuilder(128); for (String cipher : ciphers.split(":")) { javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":"); } javaCiphers.setLength(javaCiphers.length() - 1); logger.info( "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." + " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.", javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING); } return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; } } return ciphers; } static boolean isSessionCacheSupported() { return version() >= 0x10100000L; } /** * Returns a self-signed {@link X509Certificate} for {@code netty.io}. */ static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)) ); } private static boolean doesSupportOcsp() { boolean supportsOcsp = false; if (version() >= 0x10002000L) { long sslCtx = -1; try { sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER); SSLContext.enableOcsp(sslCtx, false); supportsOcsp = true; } catch (Exception ignore) { // ignore } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } return supportsOcsp; } private static boolean doesSupportProtocol(int protocol, int opt) { if (opt == 0) { // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2. return false; } long sslCtx = -1; try { sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED); return true; } catch (Exception ignore) { return false; } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } /** * Returns {@code true} if and only if * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public static boolean isAvailable() { return UNAVAILABILITY_CAUSE == null; } /** * Returns {@code true} if the used version of openssl supports * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>. * * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}. */ @Deprecated public static boolean isAlpnSupported() { return version() >= 0x10002000L; } /** * Returns {@code true} if the used version of OpenSSL supports OCSP stapling. */ public static boolean isOcspSupported() { return SUPPORTS_OCSP; } /** * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()} * returns {@code false}. */ public static int version() { return isAvailable() ? SSL.version() : -1; } /** * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()} * returns {@code false}. */ public static String versionString() { return isAvailable() ? SSL.versionString() : null; } /** * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and * its OpenSSL support are available. * * @throws UnsatisfiedLinkError if unavailable */ public static void ensureAvailability() { if (UNAVAILABILITY_CAUSE != null) { throw (Error) new UnsatisfiedLinkError( "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE); } } /** * Returns the cause of unavailability of * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support. * * @return the cause if unavailable. {@code null} if available. */ public static Throwable unavailabilityCause() { return UNAVAILABILITY_CAUSE; } /** * @deprecated use {@link #availableOpenSslCipherSuites()} */ @Deprecated public static Set<String> availableCipherSuites() { return availableOpenSslCipherSuites(); } /** * Returns all the available OpenSSL cipher suites. * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableOpenSslCipherSuites() { return AVAILABLE_OPENSSL_CIPHER_SUITES; } /** * Returns all the available cipher suites (Java-style). * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableJavaCipherSuites() { return AVAILABLE_JAVA_CIPHER_SUITES; } /** * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL. * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted. */ public static boolean isCipherSuiteAvailable(String cipherSuite) { String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL); if (converted != null) { cipherSuite = converted; } return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite); } /** * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL. */ public static boolean supportsKeyManagerFactory() { return SUPPORTS_KEYMANAGER_FACTORY; } /** * Always returns {@code true} if {@link #isAvailable()} returns {@code true}. * * @deprecated Will be removed because hostname validation is always done by a * {@link javax.net.ssl.TrustManager} implementation. */ @Deprecated public static boolean supportsHostnameValidation() { return isAvailable(); } static boolean useKeyManagerFactory() { return USE_KEYMANAGER_FACTORY; } static long memoryAddress(ByteBuf buf) { assert buf.isDirect(); return buf.hasMemoryAddress() ? buf.memoryAddress() : // Use internalNioBuffer to reduce object creation. Buffer.address(buf.internalNioBuffer(0, buf.readableBytes())); } private OpenSsl() { } private static void loadTcNative() throws Exception { String os = PlatformDependent.normalizedOs(); String arch = PlatformDependent.normalizedArch(); Set<String> libNames = new LinkedHashSet<String>(5); String staticLibName = "netty_tcnative"; // First, try loading the platform-specific library. Platform-specific // libraries will be available if using a tcnative uber jar. if ("linux".equals(os)) { Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers(); for (String classifier : classifiers) { libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier); } // generic arch-dependent library libNames.add(staticLibName + "_" + os + '_' + arch); // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0). // note: should already be included from the classifiers but if not, we use this as an // additional fallback option here libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora"); } else { libNames.add(staticLibName + "_" + os + '_' + arch); } libNames.add(staticLibName + "_" + arch); libNames.add(staticLibName); NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class), libNames.toArray(EmptyArrays.EMPTY_STRINGS)); } private static boolean initializeTcNative(String engine) throws Exception { return Library.initialize("provided", engine); } static void releaseIfNeeded(ReferenceCounted counted) { if (counted.refCnt() > 0) { ReferenceCountUtil.safeRelease(counted); } } static boolean isTlsv13Supported() { return TLSV13_SUPPORTED; } static boolean isOptionSupported(SslContextOption<?> option) { if (isAvailable()) { if (option == OpenSslContextOption.USE_TASKS) { return true; } // Check for options that are only supported by BoringSSL atm. if (isBoringSSL()) { return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD || option == OpenSslContextOption.PRIVATE_KEY_METHOD || option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS || option == OpenSslContextOption.TLS_FALSE_START || option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES; } } return false; } private static Set<String> defaultProtocols(String property) { String protocolsString = SystemPropertyUtil.get(property, null); Set<String> protocols = new HashSet<String>(); if (protocolsString != null) { for (String proto : protocolsString.split(",")) { String p = proto.trim(); protocols.add(p); } } else { protocols.add(SslProtocols.TLS_v1_2); protocols.add(SslProtocols.TLS_v1_3); } return protocols; } static String[] defaultProtocols(boolean isClient) { final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS; assert defaultProtocols != null; List<String> protocols = new ArrayList<String>(defaultProtocols.size()); for (String proto : defaultProtocols) { if (SUPPORTED_PROTOCOLS_SET.contains(proto)) { protocols.add(proto); } } return protocols.toArray(EmptyArrays.EMPTY_STRINGS); } static boolean isBoringSSL() { return IS_BORINGSSL; } }
netty/netty
handler/src/main/java/io/netty/handler/ssl/OpenSsl.java
8,169
// generic arch-dependent library
line_comment
nl
/* * Copyright 2014 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.internal.tcnative.Buffer; import io.netty.internal.tcnative.Library; import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSLContext; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.NativeLibraryLoader; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static io.netty.handler.ssl.SslUtils.*; /** * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public final class OpenSsl { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class); private static final Throwable UNAVAILABILITY_CAUSE; static final List<String> DEFAULT_CIPHERS; static final Set<String> AVAILABLE_CIPHER_SUITES; private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES; private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES; private static final boolean SUPPORTS_KEYMANAGER_FACTORY; private static final boolean USE_KEYMANAGER_FACTORY; private static final boolean SUPPORTS_OCSP; private static final boolean TLSV13_SUPPORTED; private static final boolean IS_BORINGSSL; private static final Set<String> CLIENT_DEFAULT_PROTOCOLS; private static final Set<String> SERVER_DEFAULT_PROTOCOLS; static final Set<String> SUPPORTED_PROTOCOLS_SET; static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS; static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; static final String[] NAMED_GROUPS; static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED; // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL. // See https://github.com/netty/netty-tcnative/issues/567 // See https://www.java.com/en/configure_crypto.html for ordering private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" }; static { Throwable cause = null; if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) { cause = new UnsupportedOperationException( "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true"); logger.debug( "netty-tcnative explicit disabled; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause); } else { // Test if netty-tcnative is in the classpath first. try { Class.forName("io.netty.internal.tcnative.SSLContext", false, PlatformDependent.getClassLoader(OpenSsl.class)); } catch (ClassNotFoundException t) { cause = t; logger.debug( "netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable."); } // If in the classpath, try to load the native library and initialize netty-tcnative. if (cause == null) { try { // The JNI library was not already loaded. Load it now. loadTcNative(); } catch (Throwable t) { cause = t; logger.debug( "Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " + "application has already loaded the symbols by some other means. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } try { String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null); if (engine == null) { logger.debug("Initialize netty-tcnative using engine: 'default'"); } else { logger.debug("Initialize netty-tcnative using engine: '{}'", engine); } initializeTcNative(engine); // The library was initialized successfully. If loading the library failed above, // reset the cause now since it appears that the library was loaded by some other // means. cause = null; } catch (Throwable t) { if (cause == null) { cause = t; } logger.debug( "Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. " + "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t); } } } UNAVAILABILITY_CAUSE = cause; CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols"); SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols"); if (cause == null) { logger.debug("netty-tcnative using native library: {}", SSL.versionString()); final List<String> defaultCiphers = new ArrayList<String>(); final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128); boolean supportsKeyManagerFactory = false; boolean useKeyManagerFactory = false; boolean tlsv13Supported = false; String[] namedGroups = DEFAULT_NAMED_GROUPS; String[] defaultConvertedNamedGroups = new String[namedGroups.length]; for (int i = 0; i < namedGroups.length; i++) { defaultConvertedNamedGroups[i] = GroupsConverter.toOpenSsl(namedGroups[i]); } IS_BORINGSSL = "BoringSSL".equals(versionString()); if (IS_BORINGSSL) { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384" , "TLS_CHACHA20_POLY1305_SHA256" }; StringBuilder ciphersBuilder = new StringBuilder(128); for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) { ciphersBuilder.append(cipher).append(":"); } ciphersBuilder.setLength(ciphersBuilder.length() - 1); EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString(); } else { EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; } try { final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER); long certBio = 0; long keyBio = 0; long cert = 0; long key = 0; try { // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually // handle TLSv13 as otherwise we may see runtime exceptions if (SslProvider.isTlsv13Supported(SslProvider.JDK)) { try { StringBuilder tlsv13Ciphers = new StringBuilder(); for (String cipher : TLSV13_CIPHERS) { String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL); if (converted != null) { tlsv13Ciphers.append(converted).append(':'); } } if (tlsv13Ciphers.length() == 0) { tlsv13Supported = false; } else { tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1); SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true); tlsv13Supported = true; } } catch (Exception ignore) { tlsv13Supported = false; } } SSLContext.setCipherSuite(sslCtx, "ALL", false); final long ssl = SSL.newSSL(sslCtx, true); try { for (String c: SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) || // Filter out TLSv1.3 ciphers if not supported. !tlsv13Supported && isTLSv13Cipher(c)) { continue; } availableOpenSslCipherSuites.add(c); } if (IS_BORINGSSL) { // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these // are supported. Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); Collections.addAll(availableOpenSslCipherSuites, "AEAD-AES128-GCM-SHA256", "AEAD-AES256-GCM-SHA384", "AEAD-CHACHA20-POLY1305-SHA256"); } PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII)); try { // Let's check if we can set a callback, which may not work if the used OpenSSL version // is to old. SSLContext.setCertificateCallback(sslCtx, null); X509Certificate certificate = selfSignedCertificate(); certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate); cert = SSL.parseX509Chain(certBio); keyBio = ReferenceCountedOpenSslContext.toBIO( UnpooledByteBufAllocator.DEFAULT, privateKey.retain()); key = SSL.parsePrivateKey(keyBio, null); SSL.setKeyMaterial(ssl, cert, key); supportsKeyManagerFactory = true; try { boolean propertySet = SystemPropertyUtil.contains( "io.netty.handler.ssl.openssl.useKeyManagerFactory"); if (!IS_BORINGSSL) { useKeyManagerFactory = SystemPropertyUtil.getBoolean( "io.netty.handler.ssl.openssl.useKeyManagerFactory", true); if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and so will be ignored in the future"); } } else { useKeyManagerFactory = true; if (propertySet) { logger.info("System property " + "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" + " is deprecated and will be ignored when using BoringSSL"); } } } catch (Throwable ignore) { logger.debug("Failed to get useKeyManagerFactory system property."); } } catch (Error ignore) { logger.debug("KeyManagerFactory not supported."); } finally { privateKey.release(); } } finally { SSL.freeSSL(ssl); if (certBio != 0) { SSL.freeBIO(certBio); } if (keyBio != 0) { SSL.freeBIO(keyBio); } if (cert != 0) { SSL.freeX509Chain(cert); } if (key != 0) { SSL.freePrivateKey(key); } } String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null); if (groups != null) { String[] nGroups = groups.split(","); Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length); Set<String> unsupportedNamedGroups = new LinkedHashSet<String>(); for (String namedGroup : nGroups) { String converted = GroupsConverter.toOpenSsl(namedGroup); if (SSLContext.setCurvesList(sslCtx, converted)) { supportedConvertedNamedGroups.add(converted); supportedNamedGroups.add(namedGroup); } else { unsupportedNamedGroups.add(namedGroup); } } if (supportedNamedGroups.isEmpty()) { namedGroups = defaultConvertedNamedGroups; logger.info("All configured namedGroups are not supported: {}. Use default: {}.", Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)), Arrays.toString(DEFAULT_NAMED_GROUPS)); } else { String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); if (unsupportedNamedGroups.isEmpty()) { logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ", Arrays.toString(groupArray)); } else { logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ", Arrays.toString(groupArray), Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS))); } namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS); } } else { namedGroups = defaultConvertedNamedGroups; } } finally { SSLContext.free(sslCtx); } } catch (Exception e) { logger.warn("Failed to get the list of available OpenSSL cipher suites.", e); } NAMED_GROUPS = namedGroups; AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites); final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2); for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) { // Included converted but also openssl cipher name if (!isTLSv13Cipher(cipher)) { availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS")); availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL")); } else { // TLSv1.3 ciphers have the correct format. availableJavaCipherSuites.add(cipher); } } addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES); addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES); // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL. addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites); DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers); AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites); final Set<String> availableCipherSuites = new LinkedHashSet<String>( AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size()); availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES); availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES); AVAILABLE_CIPHER_SUITES = availableCipherSuites; SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory; USE_KEYMANAGER_FACTORY = useKeyManagerFactory; Set<String> protocols = new LinkedHashSet<String>(6); // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled protocols.add(SslProtocols.SSL_v2_HELLO); if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) { protocols.add(SslProtocols.SSL_v2); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) { protocols.add(SslProtocols.SSL_v3); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) { protocols.add(SslProtocols.TLS_v1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) { protocols.add(SslProtocols.TLS_v1_1); } if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) { protocols.add(SslProtocols.TLS_v1_2); } // This is only supported by java8u272 and later. if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) { protocols.add(SslProtocols.TLS_v1_3); TLSV13_SUPPORTED = true; } else { TLSV13_SUPPORTED = false; } SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols); SUPPORTS_OCSP = doesSupportOcsp(); if (logger.isDebugEnabled()) { logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET); logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS); } // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560. boolean javaxCertificateCreationSupported; try { javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)); javaxCertificateCreationSupported = true; } catch (javax.security.cert.CertificateException ex) { javaxCertificateCreationSupported = false; } JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported; } else { DEFAULT_CIPHERS = Collections.emptyList(); AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet(); AVAILABLE_CIPHER_SUITES = Collections.emptySet(); SUPPORTS_KEYMANAGER_FACTORY = false; USE_KEYMANAGER_FACTORY = false; SUPPORTED_PROTOCOLS_SET = Collections.emptySet(); SUPPORTS_OCSP = false; TLSV13_SUPPORTED = false; IS_BORINGSSL = false; EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS; EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING; NAMED_GROUPS = DEFAULT_NAMED_GROUPS; JAVAX_CERTIFICATE_CREATION_SUPPORTED = false; } } static String checkTls13Ciphers(InternalLogger logger, String ciphers) { if (IS_BORINGSSL && !ciphers.isEmpty()) { assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0; Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length); Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS); boolean ciphersNotMatch = false; for (String cipher: ciphers.split(":")) { if (boringsslTlsv13Ciphers.isEmpty()) { ciphersNotMatch = true; break; } if (!boringsslTlsv13Ciphers.remove(cipher) && !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) { ciphersNotMatch = true; break; } } // Also check if there are ciphers left. ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty(); if (ciphersNotMatch) { if (logger.isInfoEnabled()) { StringBuilder javaCiphers = new StringBuilder(128); for (String cipher : ciphers.split(":")) { javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":"); } javaCiphers.setLength(javaCiphers.length() - 1); logger.info( "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." + " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.", javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING); } return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING; } } return ciphers; } static boolean isSessionCacheSupported() { return version() >= 0x10100000L; } /** * Returns a self-signed {@link X509Certificate} for {@code netty.io}. */ static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII)) ); } private static boolean doesSupportOcsp() { boolean supportsOcsp = false; if (version() >= 0x10002000L) { long sslCtx = -1; try { sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER); SSLContext.enableOcsp(sslCtx, false); supportsOcsp = true; } catch (Exception ignore) { // ignore } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } return supportsOcsp; } private static boolean doesSupportProtocol(int protocol, int opt) { if (opt == 0) { // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2. return false; } long sslCtx = -1; try { sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED); return true; } catch (Exception ignore) { return false; } finally { if (sslCtx != -1) { SSLContext.free(sslCtx); } } } /** * Returns {@code true} if and only if * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support * are available. */ public static boolean isAvailable() { return UNAVAILABILITY_CAUSE == null; } /** * Returns {@code true} if the used version of openssl supports * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>. * * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}. */ @Deprecated public static boolean isAlpnSupported() { return version() >= 0x10002000L; } /** * Returns {@code true} if the used version of OpenSSL supports OCSP stapling. */ public static boolean isOcspSupported() { return SUPPORTS_OCSP; } /** * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()} * returns {@code false}. */ public static int version() { return isAvailable() ? SSL.version() : -1; } /** * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()} * returns {@code false}. */ public static String versionString() { return isAvailable() ? SSL.versionString() : null; } /** * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and * its OpenSSL support are available. * * @throws UnsatisfiedLinkError if unavailable */ public static void ensureAvailability() { if (UNAVAILABILITY_CAUSE != null) { throw (Error) new UnsatisfiedLinkError( "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE); } } /** * Returns the cause of unavailability of * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support. * * @return the cause if unavailable. {@code null} if available. */ public static Throwable unavailabilityCause() { return UNAVAILABILITY_CAUSE; } /** * @deprecated use {@link #availableOpenSslCipherSuites()} */ @Deprecated public static Set<String> availableCipherSuites() { return availableOpenSslCipherSuites(); } /** * Returns all the available OpenSSL cipher suites. * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableOpenSslCipherSuites() { return AVAILABLE_OPENSSL_CIPHER_SUITES; } /** * Returns all the available cipher suites (Java-style). * Please note that the returned array may include the cipher suites that are insecure or non-functional. */ public static Set<String> availableJavaCipherSuites() { return AVAILABLE_JAVA_CIPHER_SUITES; } /** * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL. * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted. */ public static boolean isCipherSuiteAvailable(String cipherSuite) { String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL); if (converted != null) { cipherSuite = converted; } return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite); } /** * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL. */ public static boolean supportsKeyManagerFactory() { return SUPPORTS_KEYMANAGER_FACTORY; } /** * Always returns {@code true} if {@link #isAvailable()} returns {@code true}. * * @deprecated Will be removed because hostname validation is always done by a * {@link javax.net.ssl.TrustManager} implementation. */ @Deprecated public static boolean supportsHostnameValidation() { return isAvailable(); } static boolean useKeyManagerFactory() { return USE_KEYMANAGER_FACTORY; } static long memoryAddress(ByteBuf buf) { assert buf.isDirect(); return buf.hasMemoryAddress() ? buf.memoryAddress() : // Use internalNioBuffer to reduce object creation. Buffer.address(buf.internalNioBuffer(0, buf.readableBytes())); } private OpenSsl() { } private static void loadTcNative() throws Exception { String os = PlatformDependent.normalizedOs(); String arch = PlatformDependent.normalizedArch(); Set<String> libNames = new LinkedHashSet<String>(5); String staticLibName = "netty_tcnative"; // First, try loading the platform-specific library. Platform-specific // libraries will be available if using a tcnative uber jar. if ("linux".equals(os)) { Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers(); for (String classifier : classifiers) { libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier); } // generic arch-dependent<SUF> libNames.add(staticLibName + "_" + os + '_' + arch); // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0). // note: should already be included from the classifiers but if not, we use this as an // additional fallback option here libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora"); } else { libNames.add(staticLibName + "_" + os + '_' + arch); } libNames.add(staticLibName + "_" + arch); libNames.add(staticLibName); NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class), libNames.toArray(EmptyArrays.EMPTY_STRINGS)); } private static boolean initializeTcNative(String engine) throws Exception { return Library.initialize("provided", engine); } static void releaseIfNeeded(ReferenceCounted counted) { if (counted.refCnt() > 0) { ReferenceCountUtil.safeRelease(counted); } } static boolean isTlsv13Supported() { return TLSV13_SUPPORTED; } static boolean isOptionSupported(SslContextOption<?> option) { if (isAvailable()) { if (option == OpenSslContextOption.USE_TASKS) { return true; } // Check for options that are only supported by BoringSSL atm. if (isBoringSSL()) { return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD || option == OpenSslContextOption.PRIVATE_KEY_METHOD || option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS || option == OpenSslContextOption.TLS_FALSE_START || option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES; } } return false; } private static Set<String> defaultProtocols(String property) { String protocolsString = SystemPropertyUtil.get(property, null); Set<String> protocols = new HashSet<String>(); if (protocolsString != null) { for (String proto : protocolsString.split(",")) { String p = proto.trim(); protocols.add(p); } } else { protocols.add(SslProtocols.TLS_v1_2); protocols.add(SslProtocols.TLS_v1_3); } return protocols; } static String[] defaultProtocols(boolean isClient) { final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS; assert defaultProtocols != null; List<String> protocols = new ArrayList<String>(defaultProtocols.size()); for (String proto : defaultProtocols) { if (SUPPORTED_PROTOCOLS_SET.contains(proto)) { protocols.add(proto); } } return protocols.toArray(EmptyArrays.EMPTY_STRINGS); } static boolean isBoringSSL() { return IS_BORINGSSL; } }
40_6
/* * Copyright 2020 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import static io.netty.buffer.PoolThreadCache.*; /** * SizeClasses requires {@code pageShifts} to be defined prior to inclusion, * and it in turn defines: * <p> * LOG2_SIZE_CLASS_GROUP: Log of size class count for each size doubling. * LOG2_MAX_LOOKUP_SIZE: Log of max size class in the lookup table. * sizeClasses: Complete table of [index, log2Group, log2Delta, nDelta, isMultiPageSize, * isSubPage, log2DeltaLookup] tuples. * index: Size class index. * log2Group: Log of group base size (no deltas added). * log2Delta: Log of delta to previous size class. * nDelta: Delta multiplier. * isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise. * isSubPage: 'yes' if a subpage size class, 'no' otherwise. * log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no' * otherwise. * <p> * nSubpages: Number of subpages size classes. * nSizes: Number of size classes. * nPSizes: Number of size classes that are multiples of pageSize. * * smallMaxSizeIdx: Maximum small size class index. * * lookupMaxClass: Maximum size class included in lookup table. * log2NormalMinClass: Log of minimum normal size class. * <p> * The first size class and spacing are 1 << LOG2_QUANTUM. * Each group has 1 << LOG2_SIZE_CLASS_GROUP of size classes. * * size = 1 << log2Group + nDelta * (1 << log2Delta) * * The first size class has an unusual encoding, because the size has to be * split between group and delta*nDelta. * * If pageShift = 13, sizeClasses looks like this: * * (index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup) * <p> * ( 0, 4, 4, 0, no, yes, 4) * ( 1, 4, 4, 1, no, yes, 4) * ( 2, 4, 4, 2, no, yes, 4) * ( 3, 4, 4, 3, no, yes, 4) * <p> * ( 4, 6, 4, 1, no, yes, 4) * ( 5, 6, 4, 2, no, yes, 4) * ( 6, 6, 4, 3, no, yes, 4) * ( 7, 6, 4, 4, no, yes, 4) * <p> * ( 8, 7, 5, 1, no, yes, 5) * ( 9, 7, 5, 2, no, yes, 5) * ( 10, 7, 5, 3, no, yes, 5) * ( 11, 7, 5, 4, no, yes, 5) * ... * ... * ( 72, 23, 21, 1, yes, no, no) * ( 73, 23, 21, 2, yes, no, no) * ( 74, 23, 21, 3, yes, no, no) * ( 75, 23, 21, 4, yes, no, no) * <p> * ( 76, 24, 22, 1, yes, no, no) */ final class SizeClasses implements SizeClassesMetric { static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int lookupMaxSize; final int smallMaxSizeIdx; private final int[] pageIdx2sizeTab; // lookup table for sizeIdx <= smallMaxSizeIdx private final int[] sizeIdx2sizeTab; // lookup table used for size <= lookupMaxClass // spacing is 1 << LOG2_QUANTUM, so the size of array is lookupMaxClass >> LOG2_QUANTUM private final int[] size2idxTab; SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { int group = log2(chunkSize) - LOG2_QUANTUM - LOG2_SIZE_CLASS_GROUP + 1; //generate size classes //[index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup] short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; //First small group, nDelta start at 0. //first size class is 1 << LOG2_QUANTUM for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; //All remaining groups, nDelta start at 1. for (; size < chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } //chunkSize must be normalMaxSize assert chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; //generate lookup tables this.sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); this.pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); this.size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } //calculate size class private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, int pageShifts) { short isMultiPageSize; if (log2Delta >= pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << pageShifts; int size = calculateSize(log2Group, nDelta, log2Delta); isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { //size-1 / MIN_TINY return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } // Round size up to the nearest multiple of alignment. private static int alignSizeIfNeeded(int size, int directMemoryCacheAlignment) { if (directMemoryCacheAlignment <= 0) { return size; } int delta = size & directMemoryCacheAlignment - 1; return delta == 0? size : size + directMemoryCacheAlignment - delta; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int delta = 1 << log2Delta; int delta_mask = delta - 1; return size + delta_mask & ~delta_mask; } }
netty/netty
buffer/src/main/java/io/netty/buffer/SizeClasses.java
4,514
//[index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup]
line_comment
nl
/* * Copyright 2020 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer; import static io.netty.buffer.PoolThreadCache.*; /** * SizeClasses requires {@code pageShifts} to be defined prior to inclusion, * and it in turn defines: * <p> * LOG2_SIZE_CLASS_GROUP: Log of size class count for each size doubling. * LOG2_MAX_LOOKUP_SIZE: Log of max size class in the lookup table. * sizeClasses: Complete table of [index, log2Group, log2Delta, nDelta, isMultiPageSize, * isSubPage, log2DeltaLookup] tuples. * index: Size class index. * log2Group: Log of group base size (no deltas added). * log2Delta: Log of delta to previous size class. * nDelta: Delta multiplier. * isMultiPageSize: 'yes' if a multiple of the page size, 'no' otherwise. * isSubPage: 'yes' if a subpage size class, 'no' otherwise. * log2DeltaLookup: Same as log2Delta if a lookup table size class, 'no' * otherwise. * <p> * nSubpages: Number of subpages size classes. * nSizes: Number of size classes. * nPSizes: Number of size classes that are multiples of pageSize. * * smallMaxSizeIdx: Maximum small size class index. * * lookupMaxClass: Maximum size class included in lookup table. * log2NormalMinClass: Log of minimum normal size class. * <p> * The first size class and spacing are 1 << LOG2_QUANTUM. * Each group has 1 << LOG2_SIZE_CLASS_GROUP of size classes. * * size = 1 << log2Group + nDelta * (1 << log2Delta) * * The first size class has an unusual encoding, because the size has to be * split between group and delta*nDelta. * * If pageShift = 13, sizeClasses looks like this: * * (index, log2Group, log2Delta, nDelta, isMultiPageSize, isSubPage, log2DeltaLookup) * <p> * ( 0, 4, 4, 0, no, yes, 4) * ( 1, 4, 4, 1, no, yes, 4) * ( 2, 4, 4, 2, no, yes, 4) * ( 3, 4, 4, 3, no, yes, 4) * <p> * ( 4, 6, 4, 1, no, yes, 4) * ( 5, 6, 4, 2, no, yes, 4) * ( 6, 6, 4, 3, no, yes, 4) * ( 7, 6, 4, 4, no, yes, 4) * <p> * ( 8, 7, 5, 1, no, yes, 5) * ( 9, 7, 5, 2, no, yes, 5) * ( 10, 7, 5, 3, no, yes, 5) * ( 11, 7, 5, 4, no, yes, 5) * ... * ... * ( 72, 23, 21, 1, yes, no, no) * ( 73, 23, 21, 2, yes, no, no) * ( 74, 23, 21, 3, yes, no, no) * ( 75, 23, 21, 4, yes, no, no) * <p> * ( 76, 24, 22, 1, yes, no, no) */ final class SizeClasses implements SizeClassesMetric { static final int LOG2_QUANTUM = 4; private static final int LOG2_SIZE_CLASS_GROUP = 2; private static final int LOG2_MAX_LOOKUP_SIZE = 12; private static final int LOG2GROUP_IDX = 1; private static final int LOG2DELTA_IDX = 2; private static final int NDELTA_IDX = 3; private static final int PAGESIZE_IDX = 4; private static final int SUBPAGE_IDX = 5; private static final int LOG2_DELTA_LOOKUP_IDX = 6; private static final byte no = 0, yes = 1; final int pageSize; final int pageShifts; final int chunkSize; final int directMemoryCacheAlignment; final int nSizes; final int nSubpages; final int nPSizes; final int lookupMaxSize; final int smallMaxSizeIdx; private final int[] pageIdx2sizeTab; // lookup table for sizeIdx <= smallMaxSizeIdx private final int[] sizeIdx2sizeTab; // lookup table used for size <= lookupMaxClass // spacing is 1 << LOG2_QUANTUM, so the size of array is lookupMaxClass >> LOG2_QUANTUM private final int[] size2idxTab; SizeClasses(int pageSize, int pageShifts, int chunkSize, int directMemoryCacheAlignment) { int group = log2(chunkSize) - LOG2_QUANTUM - LOG2_SIZE_CLASS_GROUP + 1; //generate size classes //[index, log2Group,<SUF> short[][] sizeClasses = new short[group << LOG2_SIZE_CLASS_GROUP][7]; int normalMaxSize = -1; int nSizes = 0; int size = 0; int log2Group = LOG2_QUANTUM; int log2Delta = LOG2_QUANTUM; int ndeltaLimit = 1 << LOG2_SIZE_CLASS_GROUP; //First small group, nDelta start at 0. //first size class is 1 << LOG2_QUANTUM for (int nDelta = 0; nDelta < ndeltaLimit; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = sizeOf(sizeClass, directMemoryCacheAlignment); } log2Group += LOG2_SIZE_CLASS_GROUP; //All remaining groups, nDelta start at 1. for (; size < chunkSize; log2Group++, log2Delta++) { for (int nDelta = 1; nDelta <= ndeltaLimit && size < chunkSize; nDelta++, nSizes++) { short[] sizeClass = newSizeClass(nSizes, log2Group, log2Delta, nDelta, pageShifts); sizeClasses[nSizes] = sizeClass; size = normalMaxSize = sizeOf(sizeClass, directMemoryCacheAlignment); } } //chunkSize must be normalMaxSize assert chunkSize == normalMaxSize; int smallMaxSizeIdx = 0; int lookupMaxSize = 0; int nPSizes = 0; int nSubpages = 0; for (int idx = 0; idx < nSizes; idx++) { short[] sz = sizeClasses[idx]; if (sz[PAGESIZE_IDX] == yes) { nPSizes++; } if (sz[SUBPAGE_IDX] == yes) { nSubpages++; smallMaxSizeIdx = idx; } if (sz[LOG2_DELTA_LOOKUP_IDX] != no) { lookupMaxSize = sizeOf(sz, directMemoryCacheAlignment); } } this.smallMaxSizeIdx = smallMaxSizeIdx; this.lookupMaxSize = lookupMaxSize; this.nPSizes = nPSizes; this.nSubpages = nSubpages; this.nSizes = nSizes; this.pageSize = pageSize; this.pageShifts = pageShifts; this.chunkSize = chunkSize; this.directMemoryCacheAlignment = directMemoryCacheAlignment; //generate lookup tables this.sizeIdx2sizeTab = newIdx2SizeTab(sizeClasses, nSizes, directMemoryCacheAlignment); this.pageIdx2sizeTab = newPageIdx2sizeTab(sizeClasses, nSizes, nPSizes, directMemoryCacheAlignment); this.size2idxTab = newSize2idxTab(lookupMaxSize, sizeClasses); } //calculate size class private static short[] newSizeClass(int index, int log2Group, int log2Delta, int nDelta, int pageShifts) { short isMultiPageSize; if (log2Delta >= pageShifts) { isMultiPageSize = yes; } else { int pageSize = 1 << pageShifts; int size = calculateSize(log2Group, nDelta, log2Delta); isMultiPageSize = size == size / pageSize * pageSize? yes : no; } int log2Ndelta = nDelta == 0? 0 : log2(nDelta); byte remove = 1 << log2Ndelta < nDelta? yes : no; int log2Size = log2Delta + log2Ndelta == log2Group? log2Group + 1 : log2Group; if (log2Size == log2Group) { remove = yes; } short isSubpage = log2Size < pageShifts + LOG2_SIZE_CLASS_GROUP? yes : no; int log2DeltaLookup = log2Size < LOG2_MAX_LOOKUP_SIZE || log2Size == LOG2_MAX_LOOKUP_SIZE && remove == no ? log2Delta : no; return new short[] { (short) index, (short) log2Group, (short) log2Delta, (short) nDelta, isMultiPageSize, isSubpage, (short) log2DeltaLookup }; } private static int[] newIdx2SizeTab(short[][] sizeClasses, int nSizes, int directMemoryCacheAlignment) { int[] sizeIdx2sizeTab = new int[nSizes]; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; sizeIdx2sizeTab[i] = sizeOf(sizeClass, directMemoryCacheAlignment); } return sizeIdx2sizeTab; } private static int calculateSize(int log2Group, int nDelta, int log2Delta) { return (1 << log2Group) + (nDelta << log2Delta); } private static int sizeOf(short[] sizeClass, int directMemoryCacheAlignment) { int log2Group = sizeClass[LOG2GROUP_IDX]; int log2Delta = sizeClass[LOG2DELTA_IDX]; int nDelta = sizeClass[NDELTA_IDX]; int size = calculateSize(log2Group, nDelta, log2Delta); return alignSizeIfNeeded(size, directMemoryCacheAlignment); } private static int[] newPageIdx2sizeTab(short[][] sizeClasses, int nSizes, int nPSizes, int directMemoryCacheAlignment) { int[] pageIdx2sizeTab = new int[nPSizes]; int pageIdx = 0; for (int i = 0; i < nSizes; i++) { short[] sizeClass = sizeClasses[i]; if (sizeClass[PAGESIZE_IDX] == yes) { pageIdx2sizeTab[pageIdx++] = sizeOf(sizeClass, directMemoryCacheAlignment); } } return pageIdx2sizeTab; } private static int[] newSize2idxTab(int lookupMaxSize, short[][] sizeClasses) { int[] size2idxTab = new int[lookupMaxSize >> LOG2_QUANTUM]; int idx = 0; int size = 0; for (int i = 0; size <= lookupMaxSize; i++) { int log2Delta = sizeClasses[i][LOG2DELTA_IDX]; int times = 1 << log2Delta - LOG2_QUANTUM; while (size <= lookupMaxSize && times-- > 0) { size2idxTab[idx++] = i; size = idx + 1 << LOG2_QUANTUM; } } return size2idxTab; } @Override public int sizeIdx2size(int sizeIdx) { return sizeIdx2sizeTab[sizeIdx]; } @Override public int sizeIdx2sizeCompute(int sizeIdx) { int group = sizeIdx >> LOG2_SIZE_CLASS_GROUP; int mod = sizeIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int groupSize = group == 0? 0 : 1 << LOG2_QUANTUM + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int lgDelta = shift + LOG2_QUANTUM - 1; int modSize = mod + 1 << lgDelta; return groupSize + modSize; } @Override public long pageIdx2size(int pageIdx) { return pageIdx2sizeTab[pageIdx]; } @Override public long pageIdx2sizeCompute(int pageIdx) { int group = pageIdx >> LOG2_SIZE_CLASS_GROUP; int mod = pageIdx & (1 << LOG2_SIZE_CLASS_GROUP) - 1; long groupSize = group == 0? 0 : 1L << pageShifts + LOG2_SIZE_CLASS_GROUP - 1 << group; int shift = group == 0? 1 : group; int log2Delta = shift + pageShifts - 1; int modSize = mod + 1 << log2Delta; return groupSize + modSize; } @Override public int size2SizeIdx(int size) { if (size == 0) { return 0; } if (size > chunkSize) { return nSizes; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { //size-1 / MIN_TINY return size2idxTab[size - 1 >> LOG2_QUANTUM]; } int x = log2((size << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? 0 : x - (LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = size - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; return group + mod; } @Override public int pages2pageIdx(int pages) { return pages2pageIdxCompute(pages, false); } @Override public int pages2pageIdxFloor(int pages) { return pages2pageIdxCompute(pages, true); } private int pages2pageIdxCompute(int pages, boolean floor) { int pageSize = pages << pageShifts; if (pageSize > chunkSize) { return nPSizes; } int x = log2((pageSize << 1) - 1); int shift = x < LOG2_SIZE_CLASS_GROUP + pageShifts ? 0 : x - (LOG2_SIZE_CLASS_GROUP + pageShifts); int group = shift << LOG2_SIZE_CLASS_GROUP; int log2Delta = x < LOG2_SIZE_CLASS_GROUP + pageShifts + 1? pageShifts : x - LOG2_SIZE_CLASS_GROUP - 1; int mod = pageSize - 1 >> log2Delta & (1 << LOG2_SIZE_CLASS_GROUP) - 1; int pageIdx = group + mod; if (floor && pageIdx2sizeTab[pageIdx] > pages << pageShifts) { pageIdx--; } return pageIdx; } // Round size up to the nearest multiple of alignment. private static int alignSizeIfNeeded(int size, int directMemoryCacheAlignment) { if (directMemoryCacheAlignment <= 0) { return size; } int delta = size & directMemoryCacheAlignment - 1; return delta == 0? size : size + directMemoryCacheAlignment - delta; } @Override public int normalizeSize(int size) { if (size == 0) { return sizeIdx2sizeTab[0]; } size = alignSizeIfNeeded(size, directMemoryCacheAlignment); if (size <= lookupMaxSize) { int ret = sizeIdx2sizeTab[size2idxTab[size - 1 >> LOG2_QUANTUM]]; assert ret == normalizeSizeCompute(size); return ret; } return normalizeSizeCompute(size); } private static int normalizeSizeCompute(int size) { int x = log2((size << 1) - 1); int log2Delta = x < LOG2_SIZE_CLASS_GROUP + LOG2_QUANTUM + 1 ? LOG2_QUANTUM : x - LOG2_SIZE_CLASS_GROUP - 1; int delta = 1 << log2Delta; int delta_mask = delta - 1; return size + delta_mask & ~delta_mask; } }
89_23
// Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge between node x and node y String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
kdn251/interviews
uva/TheSettlersOfCatan.java
1,174
//get edge between node x and node y
line_comment
nl
// Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island // by building roads, settlements and cities across its uncharted wilderness. // You are employed by a software company that just has decided to develop a computer version of // this game, and you are chosen to implement one of the game’s special rules: // When the game ends, the player who built the longest road gains two extra victory points. // The problem here is that the players usually build complex road networks and not just one linear // path. Therefore, determining the longest road is not trivial (although human players usually see it // immediately). // Compared to the original game, we will solve a simplified problem here: You are given a set of nodes // (cities) and a set of edges (road segments) of length 1 connecting the nodes. // The longest road is defined as the longest path within the network that doesn’t use an edge twice. // Nodes may be visited more than once, though. // Input // The input file will contain one or more test cases. // The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the // number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the // numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected. // Nodes have degrees of three or less. The network is not neccessarily connected. // Input will be terminated by two values of 0 for n and m. // Output // For each test case, print the length of the longest road on a single line. // Sample Input // 3 2 // 0 1 // 1 2 // 15 16 // 0 2 // 1 2 // 2 3 // 3 4 // 3 5 // 4 6 // 5 7 // 6 8 // 7 8 // 7 9 // 8 10 // 9 11 // 10 12 // 11 12 // 10 13 // 12 14 // 0 0 // Sample Output // 2 // 12 import java.io.*; /** * Created by kdn251 on 2/20/17. */ public class TheSettlersOfCatan { public static int[][] matrix = new int[30][30]; public static int answer; public static void main(String args[]) throws Exception { //initialize buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; //iterate while current line is not equal to 0 0 while(!(line = br.readLine()).equals("0 0")) { //initialize number of nodes and edges int nodes = Integer.parseInt(line.split(" ")[0]); int edges = Integer.parseInt(line.split(" ")[1]); //iterate through all edges for(int i = 0; i < edges; i++) { //get edge<SUF> String[] current = br.readLine().split(" "); int x = Integer.parseInt(current[0]); int y = Integer.parseInt(current[1]); //mark edge matrix[x][y] = 1; matrix[y][x] = 1; } //initialize answer to zero answer = 0; //dfs on every node for(int i = 0; i < nodes; i++) { dfs(i, 0, nodes); } //print answer System.out.println(answer); //reset graph matrix = new int[30][30]; } } public static void dfs(int nd, int l, int nodes) { //update answer if l is larger than current answer if(l > answer) { answer = l; } for(int i = 0; i < nodes; i++) { if(matrix[nd][i] > 0) { //ensure that edge is not counted twice (like marking as "visited") matrix[nd][i] = 0; matrix[i][nd] = 0; //continue traversing graph and add 1 to count dfs(i, l + 1, nodes); //set current edge again in case node further into graph can reach it matrix[nd][i] = 1; matrix[i][nd] = 1; } } } } //source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
93_1
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find gap between elements private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/CombSort.java
632
// To find gap between elements
line_comment
nl
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { // To find<SUF> private int nextGap(int gap) { // Shrink gap by Shrink factor gap = (gap * 10) / 13; return Math.max(gap, 1); } /** * Function to sort arr[] using Comb * * @param arr - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int size = arr.length; // initialize gap int gap = size; // Initialize swapped as true to make sure that loop runs boolean swapped = true; // Keep running while gap is more than 1 and last iteration caused a swap while (gap != 1 || swapped) { // Find next gap gap = nextGap(gap); // Initialize swapped as false so that we can check if swap happened or not swapped = false; // Compare all elements with current gap for (int i = 0; i < size - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { // Swap arr[i] and arr[i+gap] SortUtils.swap(arr, i, i + gap); swapped = true; } } } return arr; } // Driver method public static void main(String[] args) { CombSort ob = new CombSort(); Integer[] arr = { 8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0, }; ob.sort(arr); System.out.println("sorted array"); SortUtils.print(arr); } }
99_7
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero to end of input value var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/others/Verhoeff.java
1,958
// Add zero to end of input value
line_comment
nl
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero<SUF> var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
315_124
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders 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 org.springframework.asm; /** * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, * and for try catch blocks. A label designates the <i>instruction</i> that is just after. Note * however that there can be other elements between a label and the instruction it designates (such * as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * A flag indicating that a label is only used for debug attributes. Such a label is not the start * of a basic block, the target of a jump instruction, or an exception handler. It can be safely * ignored in control flow graph analysis algorithms (for optimization purposes). */ static final int FLAG_DEBUG_ONLY = 1; /** * A flag indicating that a label is the target of a jump instruction, or the start of an * exception handler. */ static final int FLAG_JUMP_TARGET = 2; /** A flag indicating that the bytecode offset of a label is known. */ static final int FLAG_RESOLVED = 4; /** A flag indicating that a label corresponds to a reachable basic block. */ static final int FLAG_REACHABLE = 8; /** * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two * outgoing edges: * * <ul> * <li>the first one corresponds to the instruction that follows the jsr instruction in the * bytecode, i.e. where execution continues when it returns from the jsr call. This is a * virtual control flow edge, since execution never goes directly from the jsr to the next * instruction. Instead, it goes to the subroutine and eventually returns to the instruction * following the jsr. This virtual edge is used to compute the real outgoing edges of the * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}. * <li>the second one corresponds to the target of the jsr instruction, * </ul> */ static final int FLAG_SUBROUTINE_CALLER = 16; /** * A flag indicating that the basic block corresponding to a label is the start of a subroutine. */ static final int FLAG_SUBROUTINE_START = 32; /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */ static final int FLAG_SUBROUTINE_END = 64; /** A flag indicating that this label has at least one associated line number. */ static final int FLAG_LINE_NUMBER = 128; /** * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be * resized to store a new source line number. */ static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4; /** * The number of elements to add to the {@link #forwardReferences} array when it needs to be * resized to store a new forward reference. */ static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6; /** * The bit mask to extract the type of a forward reference to this label. The extracted type is * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. * * @see #forwardReferences */ static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; /** * The type of forward references stored with two bytes in the bytecode. This is the case, for * instance, of a forward reference from an ifnull instruction. */ static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; /** * The type of forward references stored in four bytes in the bytecode. This is the case, for * instance, of a forward reference from a lookupswitch instruction. */ static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; /** * The type of forward references stored in two bytes in the <i>stack map table</i>. This is the * case of the labels of {@link Frame#ITEM_UNINITIALIZED} stack map frame elements, when the NEW * instruction is after the &lt;init&gt; constructor call (in bytecode offset order). */ static final int FORWARD_REFERENCE_TYPE_STACK_MAP = 0x30000000; /** * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). * * @see #forwardReferences */ static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; /** * A sentinel element used to indicate the end of a list of labels. * * @see #nextListElement */ static final Label EMPTY_LIST = new Label(); /** * A user managed state associated with this label. Warning: this field is used by the ASM tree * package. In order to use it with the ASM tree package you must override the getLabelNode method * in MethodNode. */ public Object info; /** * The type and status of this label or its corresponding basic block. Must be zero or more of * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link * #FLAG_SUBROUTINE_END}. */ short flags; /** * The source line number corresponding to this label, if {@link #FLAG_LINE_NUMBER} is set. If * there are several source line numbers corresponding to this label, the first one is stored in * this field, and the remaining ones are stored in {@link #otherLineNumbers}. */ private short lineNumber; /** * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or * null. The first element of this array is the number n of source line numbers it contains, which * are stored between indices 1 and n (inclusive). */ private int[] otherLineNumbers; /** * The offset of this label in the bytecode of its method, in bytes. This value is set if and only * if the {@link #FLAG_RESOLVED} flag is set. */ int bytecodeOffset; /** * The forward references to this label. The first element is the number of forward references, * times 2 (this corresponds to the index of the last element actually used in this array). Then, * each forward reference is described with two consecutive integers noted * 'sourceInsnBytecodeOffset' and 'reference': * * <ul> * <li>'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the * forward reference, * <li>'reference' contains the type and the offset in the bytecode where the forward reference * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK} * and {@link #FORWARD_REFERENCE_HANDLE_MASK}. * </ul> * * <p>For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1 * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after * the start of the instruction itself). For the default case of a lookupswitch instruction at * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of * the instruction itself). */ private int[] forwardReferences; // ----------------------------------------------------------------------------------------------- // Fields for the control flow and data flow graph analysis algorithms (used to compute the // maximum stack size or the stack map frames). A control flow graph contains one node per "basic // block", and one edge per "jump" from one basic block to another. Each node (i.e., each basic // block) is represented with the Label object that corresponds to the first instruction of this // basic block. Each node also stores the list of its successors in the graph, as a linked list of // Edge objects. // // The control flow analysis algorithms used to compute the maximum stack size or the stack map // frames are similar and use two steps. The first step, during the visit of each instruction, // builds information about the state of the local variables and the operand stack at the end of // each basic block, called the "output frame", <i>relatively</i> to the frame state at the // beginning of the basic block, which is called the "input frame", and which is <i>unknown</i> // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm // that computes information about the input frame of each basic block, from the input state of // the first basic block (known from the method signature), and by the using the previously // computed relative output frames. // // The algorithm used to compute the maximum stack size only computes the relative output and // absolute input stack heights, while the algorithm used to compute stack map frames computes // relative output frames and absolute input frames. /** * The number of elements in the input stack of the basic block corresponding to this label. This * field is computed in {@link MethodWriter#computeMaxStackAndLocal}. */ short inputStackSize; /** * The number of elements in the output stack, at the end of the basic block corresponding to this * label. This field is only computed for basic blocks that end with a RET instruction. */ short outputStackSize; /** * The maximum height reached by the output stack, relatively to the top of the input stack, in * the basic block corresponding to this label. This maximum is always positive or {@literal * null}. */ short outputStackMax; /** * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to * several subroutines, this is the id of the "oldest" subroutine that contains it (with the * convention that a subroutine calling another one is "older" than the callee). This field is * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR * instructions. */ short subroutineId; /** * The input and output stack map frames of the basic block corresponding to this label. This * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used. */ Frame frame; /** * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}. * This linked list does not include labels used for debug info only. If the {@link * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used * then it does not contain either successive labels that denote the same bytecode offset (in this * case only the first label appears in this list). */ Label nextBasicBlock; /** * The outgoing edges of the basic block corresponding to this label, in the control flow graph of * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each * other by their {@link Edge#nextEdge} field. */ Edge outgoingEdges; /** * The next element in the list of labels to which this label belongs, or {@literal null} if it * does not belong to any list. All lists of labels must end with the {@link #EMPTY_LIST} * sentinel, in order to ensure that this field is null if and only if this label does not belong * to a list of labels. Note that there can be several lists of labels at the same time, but that * a label can belong to at most one list at a time (unless some lists share a common tail, but * this is not used in practice). * * <p>List of labels are used in {@link MethodWriter#computeAllFrames} and {@link * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size, * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these * methods, this field should be null (this property is a precondition and a postcondition of * these methods). */ Label nextListElement; // ----------------------------------------------------------------------------------------------- // Constructor and accessors // ----------------------------------------------------------------------------------------------- /** Constructs a new label. */ public Label() { // Nothing to do. } /** * Returns the bytecode offset corresponding to this label. This offset is computed from the start * of the method's bytecode. <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @return the bytecode offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((flags & FLAG_RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return bytecodeOffset; } /** * Returns the "canonical" {@link Label} instance corresponding to this label's bytecode offset, * if known, otherwise the label itself. The canonical instance is the first label (in the order * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It * cannot be known for labels which have not been visited yet. * * <p><i>This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option * is used.</i> * * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This * corresponds to the "canonical" label instance described above thanks to the way the label * frame is set in {@link MethodWriter#visitLabel}. */ final Label getCanonicalInstance() { return frame == null ? this : frame.owner; } // ----------------------------------------------------------------------------------------------- // Methods to manage line numbers // ----------------------------------------------------------------------------------------------- /** * Adds a source line number corresponding to this label. * * @param lineNumber a source line number (which should be strictly positive). */ final void addLineNumber(final int lineNumber) { if ((flags & FLAG_LINE_NUMBER) == 0) { flags |= FLAG_LINE_NUMBER; this.lineNumber = (short) lineNumber; } else { if (otherLineNumbers == null) { otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT]; } int otherLineNumberIndex = ++otherLineNumbers[0]; if (otherLineNumberIndex >= otherLineNumbers.length) { int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT]; System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length); otherLineNumbers = newLineNumbers; } otherLineNumbers[otherLineNumberIndex] = lineNumber; } } /** * Makes the given visitor visit this label and its source line numbers, if applicable. * * @param methodVisitor a method visitor. * @param visitLineNumbers whether to visit of the label's source line numbers, if any. */ final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) { methodVisitor.visitLabel(this); if (visitLineNumbers && (flags & FLAG_LINE_NUMBER) != 0) { methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this); if (otherLineNumbers != null) { for (int i = 1; i <= otherLineNumbers[0]; ++i) { methodVisitor.visitLineNumber(otherLineNumbers[i], this); } } } } // ----------------------------------------------------------------------------------------------- // Methods to compute offsets and to manage forward references // ----------------------------------------------------------------------------------------------- /** * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label * is known, the relative bytecode offset between the label and the instruction referencing it is * computed and written directly. Otherwise, a null relative offset is written and a new forward * reference is declared for this label. * * @param code the bytecode of the method. This is where the reference is appended. * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference to be appended. * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes). */ final void put( final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) { if ((flags & FLAG_RESOLVED) == 0) { if (wideReference) { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length); code.putInt(-1); } else { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length); code.putShort(-1); } } else { if (wideReference) { code.putInt(bytecodeOffset - sourceInsnBytecodeOffset); } else { code.putShort(bytecodeOffset - sourceInsnBytecodeOffset); } } } /** * Puts a reference to this label in the <i>stack map table</i> of a method. If the bytecode * offset of the label is known, it is written directly. Otherwise, a null relative offset is * written and a new forward reference is declared for this label. * * @param stackMapTableEntries the stack map table where the label offset must be added. */ final void put(final ByteVector stackMapTableEntries) { if ((flags & FLAG_RESOLVED) == 0) { addForwardReference(0, FORWARD_REFERENCE_TYPE_STACK_MAP, stackMapTableEntries.length); } stackMapTableEntries.putShort(bytecodeOffset); } /** * Adds a forward reference to this label. This method must be called only for a true forward * reference, i.e. only if this label is not resolved yet. For backward references, the relative * bytecode offset of the reference can be, and must be, computed and stored directly. * * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference stored at referenceHandle. * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link * #FORWARD_REFERENCE_TYPE_WIDE}. * @param referenceHandle the offset in the bytecode where the forward reference value must be * stored. */ private void addForwardReference( final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) { if (forwardReferences == null) { forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT]; } int lastElementIndex = forwardReferences[0]; if (lastElementIndex + 2 >= forwardReferences.length) { int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT]; System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length); forwardReferences = newValues; } forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset; forwardReferences[++lastElementIndex] = referenceType | referenceHandle; forwardReferences[0] = lastElementIndex; } /** * Sets the bytecode offset of this label to the given value and resolves the forward references * to this label, if any. This method must be called when this label is added to the bytecode of * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that * where left in the bytecode (and optionally in the stack map table) by each forward reference * previously added to this label. * * @param code the bytecode of the method. * @param stackMapTableEntries the 'entries' array of the StackMapTable code attribute of the * method. Maybe {@literal null}. * @param bytecodeOffset the bytecode offset of this label. * @return {@literal true} if a blank that was left for this label was too small to store the * offset. In such a case the corresponding jump instruction is replaced with an equivalent * ASM specific instruction using an unsigned two bytes offset. These ASM specific * instructions are later replaced with standard bytecode instructions with wider offsets (4 * bytes instead of 2), in ClassReader. */ final boolean resolve( final byte[] code, final ByteVector stackMapTableEntries, final int bytecodeOffset) { this.flags |= FLAG_RESOLVED; this.bytecodeOffset = bytecodeOffset; if (forwardReferences == null) { return false; } boolean hasAsmInstructions = false; for (int i = forwardReferences[0]; i > 0; i -= 2) { final int sourceInsnBytecodeOffset = forwardReferences[i - 1]; final int reference = forwardReferences[i]; final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset; int handle = reference & FORWARD_REFERENCE_HANDLE_MASK; if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) { // Change the opcode of the jump instruction, in order to be able to find it later in // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to // 65535, which is sufficient since the size of a method is limited to 65535 bytes). int opcode = code[sourceInsnBytecodeOffset] & 0xFF; if (opcode < Opcodes.IFNULL) { // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA); } else { // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA); } hasAsmInstructions = true; } code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_WIDE) { code[handle++] = (byte) (relativeOffset >>> 24); code[handle++] = (byte) (relativeOffset >>> 16); code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else { stackMapTableEntries.data[handle++] = (byte) (bytecodeOffset >>> 8); stackMapTableEntries.data[handle] = (byte) bytecodeOffset; } } return hasAsmInstructions; } // ----------------------------------------------------------------------------------------------- // Methods related to subroutines // ----------------------------------------------------------------------------------------------- /** * Finds the basic blocks that belong to the subroutine starting with the basic block * corresponding to this label, and marks these blocks as belonging to this subroutine. This * method follows the control flow graph to find all the blocks that are reachable from the * current basic block WITHOUT following any jsr target. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineId the id of the subroutine starting with the basic block corresponding to * this label. */ final void markSubroutine(final short subroutineId) { // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the // control flow graph to the list of blocks to process (if not already done). Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; basicBlock.nextListElement = null; // If it is not already marked as belonging to a subroutine, mark it as belonging to // subroutineId and add its successors to the list of blocks to process (unless already done). if (basicBlock.subroutineId == 0) { basicBlock.subroutineId = subroutineId; listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } } } /** * Finds the basic blocks that end a subroutine starting with the basic block corresponding to * this label and, for each one of them, adds an outgoing edge to the basic block following the * given subroutine call. In other words, completes the control flow graph by adding the edges * corresponding to the return from this subroutine, when called from the given caller basic * block. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to * this label. This label is supposed to correspond to the start of a subroutine. */ final void addSubroutineRetSuccessors(final Label subroutineCaller) { // Data flow algorithm: put this basic block in a list blocks to process (which are blocks // belonging to a subroutine starting with this label) and, while there are blocks to process, // remove one from the list, put it in a list of blocks that have been processed, add a return // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks // in the control flow graph to the list of blocks to process (if not already done). Label listOfProcessedBlocks = EMPTY_LIST; Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Move a basic block from the list of blocks to process to the list of processed blocks. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = basicBlock.nextListElement; basicBlock.nextListElement = listOfProcessedBlocks; listOfProcessedBlocks = basicBlock; // Add an edge from this block to the successor of the caller basic block, if this block is // the end of a subroutine and if this block and subroutineCaller do not belong to the same // subroutine. if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 && basicBlock.subroutineId != subroutineCaller.subroutineId) { basicBlock.outgoingEdges = new Edge( basicBlock.outputStackSize, // By construction, the first outgoing edge of a basic block that ends with a jsr // instruction leads to the jsr continuation block, i.e. where execution continues // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). subroutineCaller.outgoingEdges.successor, basicBlock.outgoingEdges); } // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does // not push basic blocks which are already in a list. Here this means either in the list of // blocks to process, or in the list of already processed blocks. This second list is // important to make sure we don't reprocess an already processed block. listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, // so that this method can be called again with a different subroutine or subroutine caller. while (listOfProcessedBlocks != EMPTY_LIST) { Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement; listOfProcessedBlocks.nextListElement = null; listOfProcessedBlocks = newListOfProcessedBlocks; } } /** * Adds the successors of this label in the method's control flow graph (except those * corresponding to a jsr target, and those already in a list of labels) to the given list of * blocks to process, and returns the new list. * * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their * {@link #nextListElement} field. * @return the new list of blocks to process. */ private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; newListOfLabelsToProcess = outgoingEdge.successor; } outgoingEdge = outgoingEdge.nextEdge; } return newListOfLabelsToProcess; } // ----------------------------------------------------------------------------------------------- // Overridden Object methods // ----------------------------------------------------------------------------------------------- /** * Returns a string representation of this label. * * @return a string representation of this label. */ @Override public String toString() { return "L" + System.identityHashCode(this); } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Label.java
7,954
// Overridden Object methods
line_comment
nl
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders 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 org.springframework.asm; /** * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, * and for try catch blocks. A label designates the <i>instruction</i> that is just after. Note * however that there can be other elements between a label and the instruction it designates (such * as other labels, stack map frames, line numbers, etc.). * * @author Eric Bruneton */ public class Label { /** * A flag indicating that a label is only used for debug attributes. Such a label is not the start * of a basic block, the target of a jump instruction, or an exception handler. It can be safely * ignored in control flow graph analysis algorithms (for optimization purposes). */ static final int FLAG_DEBUG_ONLY = 1; /** * A flag indicating that a label is the target of a jump instruction, or the start of an * exception handler. */ static final int FLAG_JUMP_TARGET = 2; /** A flag indicating that the bytecode offset of a label is known. */ static final int FLAG_RESOLVED = 4; /** A flag indicating that a label corresponds to a reachable basic block. */ static final int FLAG_REACHABLE = 8; /** * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two * outgoing edges: * * <ul> * <li>the first one corresponds to the instruction that follows the jsr instruction in the * bytecode, i.e. where execution continues when it returns from the jsr call. This is a * virtual control flow edge, since execution never goes directly from the jsr to the next * instruction. Instead, it goes to the subroutine and eventually returns to the instruction * following the jsr. This virtual edge is used to compute the real outgoing edges of the * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}. * <li>the second one corresponds to the target of the jsr instruction, * </ul> */ static final int FLAG_SUBROUTINE_CALLER = 16; /** * A flag indicating that the basic block corresponding to a label is the start of a subroutine. */ static final int FLAG_SUBROUTINE_START = 32; /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */ static final int FLAG_SUBROUTINE_END = 64; /** A flag indicating that this label has at least one associated line number. */ static final int FLAG_LINE_NUMBER = 128; /** * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be * resized to store a new source line number. */ static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4; /** * The number of elements to add to the {@link #forwardReferences} array when it needs to be * resized to store a new forward reference. */ static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6; /** * The bit mask to extract the type of a forward reference to this label. The extracted type is * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. * * @see #forwardReferences */ static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; /** * The type of forward references stored with two bytes in the bytecode. This is the case, for * instance, of a forward reference from an ifnull instruction. */ static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; /** * The type of forward references stored in four bytes in the bytecode. This is the case, for * instance, of a forward reference from a lookupswitch instruction. */ static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; /** * The type of forward references stored in two bytes in the <i>stack map table</i>. This is the * case of the labels of {@link Frame#ITEM_UNINITIALIZED} stack map frame elements, when the NEW * instruction is after the &lt;init&gt; constructor call (in bytecode offset order). */ static final int FORWARD_REFERENCE_TYPE_STACK_MAP = 0x30000000; /** * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). * * @see #forwardReferences */ static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; /** * A sentinel element used to indicate the end of a list of labels. * * @see #nextListElement */ static final Label EMPTY_LIST = new Label(); /** * A user managed state associated with this label. Warning: this field is used by the ASM tree * package. In order to use it with the ASM tree package you must override the getLabelNode method * in MethodNode. */ public Object info; /** * The type and status of this label or its corresponding basic block. Must be zero or more of * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link * #FLAG_SUBROUTINE_END}. */ short flags; /** * The source line number corresponding to this label, if {@link #FLAG_LINE_NUMBER} is set. If * there are several source line numbers corresponding to this label, the first one is stored in * this field, and the remaining ones are stored in {@link #otherLineNumbers}. */ private short lineNumber; /** * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or * null. The first element of this array is the number n of source line numbers it contains, which * are stored between indices 1 and n (inclusive). */ private int[] otherLineNumbers; /** * The offset of this label in the bytecode of its method, in bytes. This value is set if and only * if the {@link #FLAG_RESOLVED} flag is set. */ int bytecodeOffset; /** * The forward references to this label. The first element is the number of forward references, * times 2 (this corresponds to the index of the last element actually used in this array). Then, * each forward reference is described with two consecutive integers noted * 'sourceInsnBytecodeOffset' and 'reference': * * <ul> * <li>'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the * forward reference, * <li>'reference' contains the type and the offset in the bytecode where the forward reference * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK} * and {@link #FORWARD_REFERENCE_HANDLE_MASK}. * </ul> * * <p>For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1 * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after * the start of the instruction itself). For the default case of a lookupswitch instruction at * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of * the instruction itself). */ private int[] forwardReferences; // ----------------------------------------------------------------------------------------------- // Fields for the control flow and data flow graph analysis algorithms (used to compute the // maximum stack size or the stack map frames). A control flow graph contains one node per "basic // block", and one edge per "jump" from one basic block to another. Each node (i.e., each basic // block) is represented with the Label object that corresponds to the first instruction of this // basic block. Each node also stores the list of its successors in the graph, as a linked list of // Edge objects. // // The control flow analysis algorithms used to compute the maximum stack size or the stack map // frames are similar and use two steps. The first step, during the visit of each instruction, // builds information about the state of the local variables and the operand stack at the end of // each basic block, called the "output frame", <i>relatively</i> to the frame state at the // beginning of the basic block, which is called the "input frame", and which is <i>unknown</i> // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm // that computes information about the input frame of each basic block, from the input state of // the first basic block (known from the method signature), and by the using the previously // computed relative output frames. // // The algorithm used to compute the maximum stack size only computes the relative output and // absolute input stack heights, while the algorithm used to compute stack map frames computes // relative output frames and absolute input frames. /** * The number of elements in the input stack of the basic block corresponding to this label. This * field is computed in {@link MethodWriter#computeMaxStackAndLocal}. */ short inputStackSize; /** * The number of elements in the output stack, at the end of the basic block corresponding to this * label. This field is only computed for basic blocks that end with a RET instruction. */ short outputStackSize; /** * The maximum height reached by the output stack, relatively to the top of the input stack, in * the basic block corresponding to this label. This maximum is always positive or {@literal * null}. */ short outputStackMax; /** * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to * several subroutines, this is the id of the "oldest" subroutine that contains it (with the * convention that a subroutine calling another one is "older" than the callee). This field is * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR * instructions. */ short subroutineId; /** * The input and output stack map frames of the basic block corresponding to this label. This * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used. */ Frame frame; /** * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}. * This linked list does not include labels used for debug info only. If the {@link * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used * then it does not contain either successive labels that denote the same bytecode offset (in this * case only the first label appears in this list). */ Label nextBasicBlock; /** * The outgoing edges of the basic block corresponding to this label, in the control flow graph of * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each * other by their {@link Edge#nextEdge} field. */ Edge outgoingEdges; /** * The next element in the list of labels to which this label belongs, or {@literal null} if it * does not belong to any list. All lists of labels must end with the {@link #EMPTY_LIST} * sentinel, in order to ensure that this field is null if and only if this label does not belong * to a list of labels. Note that there can be several lists of labels at the same time, but that * a label can belong to at most one list at a time (unless some lists share a common tail, but * this is not used in practice). * * <p>List of labels are used in {@link MethodWriter#computeAllFrames} and {@link * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size, * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these * methods, this field should be null (this property is a precondition and a postcondition of * these methods). */ Label nextListElement; // ----------------------------------------------------------------------------------------------- // Constructor and accessors // ----------------------------------------------------------------------------------------------- /** Constructs a new label. */ public Label() { // Nothing to do. } /** * Returns the bytecode offset corresponding to this label. This offset is computed from the start * of the method's bytecode. <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @return the bytecode offset corresponding to this label. * @throws IllegalStateException if this label is not resolved yet. */ public int getOffset() { if ((flags & FLAG_RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return bytecodeOffset; } /** * Returns the "canonical" {@link Label} instance corresponding to this label's bytecode offset, * if known, otherwise the label itself. The canonical instance is the first label (in the order * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It * cannot be known for labels which have not been visited yet. * * <p><i>This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option * is used.</i> * * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This * corresponds to the "canonical" label instance described above thanks to the way the label * frame is set in {@link MethodWriter#visitLabel}. */ final Label getCanonicalInstance() { return frame == null ? this : frame.owner; } // ----------------------------------------------------------------------------------------------- // Methods to manage line numbers // ----------------------------------------------------------------------------------------------- /** * Adds a source line number corresponding to this label. * * @param lineNumber a source line number (which should be strictly positive). */ final void addLineNumber(final int lineNumber) { if ((flags & FLAG_LINE_NUMBER) == 0) { flags |= FLAG_LINE_NUMBER; this.lineNumber = (short) lineNumber; } else { if (otherLineNumbers == null) { otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT]; } int otherLineNumberIndex = ++otherLineNumbers[0]; if (otherLineNumberIndex >= otherLineNumbers.length) { int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT]; System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length); otherLineNumbers = newLineNumbers; } otherLineNumbers[otherLineNumberIndex] = lineNumber; } } /** * Makes the given visitor visit this label and its source line numbers, if applicable. * * @param methodVisitor a method visitor. * @param visitLineNumbers whether to visit of the label's source line numbers, if any. */ final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) { methodVisitor.visitLabel(this); if (visitLineNumbers && (flags & FLAG_LINE_NUMBER) != 0) { methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this); if (otherLineNumbers != null) { for (int i = 1; i <= otherLineNumbers[0]; ++i) { methodVisitor.visitLineNumber(otherLineNumbers[i], this); } } } } // ----------------------------------------------------------------------------------------------- // Methods to compute offsets and to manage forward references // ----------------------------------------------------------------------------------------------- /** * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label * is known, the relative bytecode offset between the label and the instruction referencing it is * computed and written directly. Otherwise, a null relative offset is written and a new forward * reference is declared for this label. * * @param code the bytecode of the method. This is where the reference is appended. * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference to be appended. * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes). */ final void put( final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) { if ((flags & FLAG_RESOLVED) == 0) { if (wideReference) { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length); code.putInt(-1); } else { addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length); code.putShort(-1); } } else { if (wideReference) { code.putInt(bytecodeOffset - sourceInsnBytecodeOffset); } else { code.putShort(bytecodeOffset - sourceInsnBytecodeOffset); } } } /** * Puts a reference to this label in the <i>stack map table</i> of a method. If the bytecode * offset of the label is known, it is written directly. Otherwise, a null relative offset is * written and a new forward reference is declared for this label. * * @param stackMapTableEntries the stack map table where the label offset must be added. */ final void put(final ByteVector stackMapTableEntries) { if ((flags & FLAG_RESOLVED) == 0) { addForwardReference(0, FORWARD_REFERENCE_TYPE_STACK_MAP, stackMapTableEntries.length); } stackMapTableEntries.putShort(bytecodeOffset); } /** * Adds a forward reference to this label. This method must be called only for a true forward * reference, i.e. only if this label is not resolved yet. For backward references, the relative * bytecode offset of the reference can be, and must be, computed and stored directly. * * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the * reference stored at referenceHandle. * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link * #FORWARD_REFERENCE_TYPE_WIDE}. * @param referenceHandle the offset in the bytecode where the forward reference value must be * stored. */ private void addForwardReference( final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) { if (forwardReferences == null) { forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT]; } int lastElementIndex = forwardReferences[0]; if (lastElementIndex + 2 >= forwardReferences.length) { int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT]; System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length); forwardReferences = newValues; } forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset; forwardReferences[++lastElementIndex] = referenceType | referenceHandle; forwardReferences[0] = lastElementIndex; } /** * Sets the bytecode offset of this label to the given value and resolves the forward references * to this label, if any. This method must be called when this label is added to the bytecode of * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that * where left in the bytecode (and optionally in the stack map table) by each forward reference * previously added to this label. * * @param code the bytecode of the method. * @param stackMapTableEntries the 'entries' array of the StackMapTable code attribute of the * method. Maybe {@literal null}. * @param bytecodeOffset the bytecode offset of this label. * @return {@literal true} if a blank that was left for this label was too small to store the * offset. In such a case the corresponding jump instruction is replaced with an equivalent * ASM specific instruction using an unsigned two bytes offset. These ASM specific * instructions are later replaced with standard bytecode instructions with wider offsets (4 * bytes instead of 2), in ClassReader. */ final boolean resolve( final byte[] code, final ByteVector stackMapTableEntries, final int bytecodeOffset) { this.flags |= FLAG_RESOLVED; this.bytecodeOffset = bytecodeOffset; if (forwardReferences == null) { return false; } boolean hasAsmInstructions = false; for (int i = forwardReferences[0]; i > 0; i -= 2) { final int sourceInsnBytecodeOffset = forwardReferences[i - 1]; final int reference = forwardReferences[i]; final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset; int handle = reference & FORWARD_REFERENCE_HANDLE_MASK; if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) { // Change the opcode of the jump instruction, in order to be able to find it later in // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to // 65535, which is sufficient since the size of a method is limited to 65535 bytes). int opcode = code[sourceInsnBytecodeOffset] & 0xFF; if (opcode < Opcodes.IFNULL) { // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA); } else { // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA); } hasAsmInstructions = true; } code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_WIDE) { code[handle++] = (byte) (relativeOffset >>> 24); code[handle++] = (byte) (relativeOffset >>> 16); code[handle++] = (byte) (relativeOffset >>> 8); code[handle] = (byte) relativeOffset; } else { stackMapTableEntries.data[handle++] = (byte) (bytecodeOffset >>> 8); stackMapTableEntries.data[handle] = (byte) bytecodeOffset; } } return hasAsmInstructions; } // ----------------------------------------------------------------------------------------------- // Methods related to subroutines // ----------------------------------------------------------------------------------------------- /** * Finds the basic blocks that belong to the subroutine starting with the basic block * corresponding to this label, and marks these blocks as belonging to this subroutine. This * method follows the control flow graph to find all the blocks that are reachable from the * current basic block WITHOUT following any jsr target. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineId the id of the subroutine starting with the basic block corresponding to * this label. */ final void markSubroutine(final short subroutineId) { // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the // control flow graph to the list of blocks to process (if not already done). Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; basicBlock.nextListElement = null; // If it is not already marked as belonging to a subroutine, mark it as belonging to // subroutineId and add its successors to the list of blocks to process (unless already done). if (basicBlock.subroutineId == 0) { basicBlock.subroutineId = subroutineId; listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } } } /** * Finds the basic blocks that end a subroutine starting with the basic block corresponding to * this label and, for each one of them, adds an outgoing edge to the basic block following the * given subroutine call. In other words, completes the control flow graph by adding the edges * corresponding to the return from this subroutine, when called from the given caller basic * block. * * <p>Note: a precondition and postcondition of this method is that all labels must have a null * {@link #nextListElement}. * * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to * this label. This label is supposed to correspond to the start of a subroutine. */ final void addSubroutineRetSuccessors(final Label subroutineCaller) { // Data flow algorithm: put this basic block in a list blocks to process (which are blocks // belonging to a subroutine starting with this label) and, while there are blocks to process, // remove one from the list, put it in a list of blocks that have been processed, add a return // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks // in the control flow graph to the list of blocks to process (if not already done). Label listOfProcessedBlocks = EMPTY_LIST; Label listOfBlocksToProcess = this; listOfBlocksToProcess.nextListElement = EMPTY_LIST; while (listOfBlocksToProcess != EMPTY_LIST) { // Move a basic block from the list of blocks to process to the list of processed blocks. Label basicBlock = listOfBlocksToProcess; listOfBlocksToProcess = basicBlock.nextListElement; basicBlock.nextListElement = listOfProcessedBlocks; listOfProcessedBlocks = basicBlock; // Add an edge from this block to the successor of the caller basic block, if this block is // the end of a subroutine and if this block and subroutineCaller do not belong to the same // subroutine. if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 && basicBlock.subroutineId != subroutineCaller.subroutineId) { basicBlock.outgoingEdges = new Edge( basicBlock.outputStackSize, // By construction, the first outgoing edge of a basic block that ends with a jsr // instruction leads to the jsr continuation block, i.e. where execution continues // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). subroutineCaller.outgoingEdges.successor, basicBlock.outgoingEdges); } // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does // not push basic blocks which are already in a list. Here this means either in the list of // blocks to process, or in the list of already processed blocks. This second list is // important to make sure we don't reprocess an already processed block. listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); } // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, // so that this method can be called again with a different subroutine or subroutine caller. while (listOfProcessedBlocks != EMPTY_LIST) { Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement; listOfProcessedBlocks.nextListElement = null; listOfProcessedBlocks = newListOfProcessedBlocks; } } /** * Adds the successors of this label in the method's control flow graph (except those * corresponding to a jsr target, and those already in a list of labels) to the given list of * blocks to process, and returns the new list. * * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their * {@link #nextListElement} field. * @return the new list of blocks to process. */ private Label pushSuccessors(final Label listOfLabelsToProcess) { Label newListOfLabelsToProcess = listOfLabelsToProcess; Edge outgoingEdge = outgoingEdges; while (outgoingEdge != null) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; newListOfLabelsToProcess = outgoingEdge.successor; } outgoingEdge = outgoingEdge.nextEdge; } return newListOfLabelsToProcess; } // ----------------------------------------------------------------------------------------------- // Overridden Object<SUF> // ----------------------------------------------------------------------------------------------- /** * Returns a string representation of this label. * * @return a string representation of this label. */ @Override public String toString() { return "L" + System.identityHashCode(this); } }
346_0
///usr/bin/env jbang "$0" "$@" ; exit $? // //DEPS <dependency1> <dependency2> import static java.lang.System.*; public class hello { public static void main(String... args) { out.println("Hello World"); } }
eugenp/tutorials
jbang/hello.java
70
///usr/bin/env jbang "$0" "$@" ; exit $?
line_comment
nl
///usr/bin/env jbang<SUF> // //DEPS <dependency1> <dependency2> import static java.lang.System.*; public class hello { public static void main(String... args) { out.println("Hello World"); } }
404_9
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite; /** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */ public enum DataType { /** 32-bit single precision floating point. */ FLOAT32(1), /** 32-bit signed integer. */ INT32(2), /** 8-bit unsigned integer. */ UINT8(3), /** 64-bit signed integer. */ INT64(4), /** Strings. */ STRING(5), /** Bool. */ BOOL(6), /** 16-bit signed integer. */ INT16(7), /** 8-bit signed integer. */ INT8(9); private final int value; DataType(int value) { this.value = value; } /** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */ public int byteSize() { switch (this) { case FLOAT32: case INT32: return 4; case INT16: return 2; case INT8: case UINT8: return 1; case INT64: return 8; case BOOL: // Boolean size is JVM-dependent. return -1; case STRING: return -1; } throw new IllegalArgumentException( "DataType error: DataType " + this + " is not supported yet"); } /** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */ int c() { return value; } }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/DataType.java
544
// Boolean size is JVM-dependent.
line_comment
nl
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package org.tensorflow.lite; /** Represents the type of elements in a TensorFlow Lite {@link Tensor} as an enum. */ public enum DataType { /** 32-bit single precision floating point. */ FLOAT32(1), /** 32-bit signed integer. */ INT32(2), /** 8-bit unsigned integer. */ UINT8(3), /** 64-bit signed integer. */ INT64(4), /** Strings. */ STRING(5), /** Bool. */ BOOL(6), /** 16-bit signed integer. */ INT16(7), /** 8-bit signed integer. */ INT8(9); private final int value; DataType(int value) { this.value = value; } /** Returns the size of an element of this type, in bytes, or -1 if element size is variable. */ public int byteSize() { switch (this) { case FLOAT32: case INT32: return 4; case INT16: return 2; case INT8: case UINT8: return 1; case INT64: return 8; case BOOL: // Boolean size<SUF> return -1; case STRING: return -1; } throw new IllegalArgumentException( "DataType error: DataType " + this + " is not supported yet"); } /** Corresponding value of the TfLiteType enum in the TensorFlow Lite C API. */ int c() { return value; } }
448_6
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 // class to generate data only import java.io.*; import java.util.*; class FeaturePlus { Feature feat; int feat_arc_index; FeaturePlus(Feature f, int fai) { feat = f; feat_arc_index = fai; } } class Generate implements Debuggable { public static Random R = new Random(); public static int SEPARATION_INDEX = 0; public static String KEY_HELP = "--help", KEY_GENERATOR_LINK = "-L", KEY_NUMBER_EXAMPLES = "-N", KEY_DIRECTORY = "-D", KEY_PREFIX = "-P", KEY_X = "-X", KEY_Y = "-Y", SEP = "/", KEY_FORCE_INTEGER_CODING = "-F", KEY_UNKNOWN_VALUE_CODING = "-U"; public static String KEY_NODES = "@NODES", KEY_ARCS = "@ARCS"; String generator_file, x_name, y_name, statistics_experiment, directory_data, prefix_data, generator_name, unknown_v_coding; boolean force_int_coding; int number_ex, x_index, y_index; Wrapper wrap; Generate( String xn, String yn, String dir, String pref, String gen_name, boolean force_int_coding, String unknown_v_coding) { statistics_experiment = null; x_name = xn; y_name = yn; directory_data = dir; prefix_data = pref; generator_name = gen_name; generator_file = null; this.force_int_coding = force_int_coding; if (unknown_v_coding.equals("")) this.unknown_v_coding = "-1"; else this.unknown_v_coding = unknown_v_coding; wrap = null; x_index = y_index = -1; } public static String help() { String ret = ""; ret += KEY_HELP + " : example command line\n\n"; ret += "java -Xmx10000m Generate -D Datasets/generate/ -P open_policing_hartford -U NA -F true -N" + " 1000 -L example-generator_open_policing_hartford.csv\n\n"; ret += KEY_DIRECTORY + " (String) :: mandatory -- directory where to find the resource below\n"; ret += KEY_PREFIX + " (String) :: mandatory -- prefix of the domain (the .csv datafile must be at" + " Datasets/generate/open_policing_hartford.csv)\n"; ret += KEY_UNKNOWN_VALUE_CODING + " (String) :: optional -- representation of 'unknown' value in dataset -- default:" + " \"-1\"\n"; ret += KEY_FORCE_INTEGER_CODING + " (boolean) :: optional -- if true, recognizes integer variables and codes them as" + " such (otherwise, codes them as doubles) -- default: false\n"; ret += KEY_GENERATOR_LINK + " (String) :: mandatory -- file containing the generator to be used (the file must be" + " in directory Datasets/generate/open_policing_hartford/)\n"; ret += KEY_NUMBER_EXAMPLES + " (integer) :: optional -- #examples to be generated (the file name will be at the" + " same location as generator, with name ending in '_GeneratedSample.csv'; if" + " unspecified, just displays generator)\n"; ret += KEY_X + " (String) :: optional -- variable name in x value for xy density plot of generated" + " data\n"; ret += KEY_Y + " (String) :: optional -- variable name in y value for xy density plot of generated" + " data\n"; return ret; } public static void main(String[] arg) { int i; String generator_n = ""; int number_ex = -1; boolean kF = false; String kD = "", kP = "", kU = "", xn = null, yn = null; System.out.println(""); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); System.out.println( "// Companion code to ICML'22 paper \"Generative Trees: Adversarial and Copycat\", by" + " Richard Nock and Mathieu Guillame-Bert //"); System.out.println( "// (generating examples from a generative tree; to *train* a generative tree, try 'java" + " Wrapper --help') //"); if (arg.length == 0) { System.out.println("// *No parameters*. Run 'java Generate --help' for more"); System.exit(0); } System.out.println( "// Help & example run: 'java Generate --help' " + " //"); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); for (i = 0; i < arg.length; i++) { if (arg[i].equals(KEY_HELP)) { Dataset.perror(help()); } else if (arg[i].equals(KEY_GENERATOR_LINK)) { generator_n = arg[i + 1]; } else if (arg[i].equals(KEY_DIRECTORY)) { kD = arg[i + 1]; } else if (arg[i].equals(KEY_PREFIX)) { kP = arg[i + 1]; } else if (arg[i].equals(KEY_UNKNOWN_VALUE_CODING)) { kU = arg[i + 1]; } else if (arg[i].equals(KEY_FORCE_INTEGER_CODING)) { kF = Boolean.parseBoolean(arg[i + 1]); } else if (arg[i].equals(KEY_NUMBER_EXAMPLES)) { number_ex = Integer.parseInt(arg[i + 1]); } else if (arg[i].equals(KEY_X)) { xn = new String(arg[i + 1]); } else if (arg[i].equals(KEY_Y)) { yn = new String(arg[i + 1]); } } if (generator_n.equals("")) Dataset.perror("Generate.class :: no sample to generate, check parameters"); if (kD.equals("")) Dataset.perror("Generate.class :: no directory, check parameters"); if (kP.equals("")) Dataset.perror("Generate.class :: no prefix, check parameters"); if (number_ex <= 0) Dataset.warning("Experiment.class :: no example generation"); Generate ee = new Generate(xn, yn, kD, kP, generator_n, kF, kU); ee.go(number_ex); System.out.println("\nBibTex:"); System.out.println("@inproceedings{ngbGT,"); System.out.println(" title={Generative Trees: Adversarial and Copycat},"); System.out.println(" author={R. Nock and M. Guillame-Bert},"); System.out.println(" booktitle={39$^{~th}$ International Conference on Machine Learning},"); System.out.println(" year={2022}"); System.out.println("}\n"); } public void go(int nex) { number_ex = nex; wrap = new Wrapper(); wrap.force_integer_coding = force_int_coding; Unknown_Feature_Value.S_UNKNOWN = unknown_v_coding; wrap.path_and_name_of_domain_dataset = directory_data + prefix_data + SEP + prefix_data + ".csv"; wrap.myDomain = new Domain(wrap); generator_file = directory_data + prefix_data + SEP + generator_name; System.out.println("Datafile at " + wrap.path_and_name_of_domain_dataset); System.out.println("Generator at " + generator_file); Generator_Tree gt = from_file(wrap.myDomain); System.out.println("GT loaded:"); System.out.println(gt); if (number_ex > 0) { System.out.print("\nGenerating " + number_ex + " examples... "); Vector<Example> v_gen; if (((x_name != null) && (!x_name.equals(""))) && ((y_name != null) && (!y_name.equals("")))) v_gen = gt.generate_sample_with_density(number_ex); else v_gen = gt.generate_sample(number_ex); String save_sample_csv = directory_data + prefix_data + SEP + prefix_data + "_GeneratedSample.csv"; String save_sample_density_plot_csv; System.out.print("ok.\nSaving generated sample in file " + save_sample_csv + " ..."); to_file(v_gen, save_sample_csv, false, -1, -1); System.out.println(" ok."); if ((x_name != null) && (y_name != null)) { save_sample_density_plot_csv = directory_data + prefix_data + SEP + prefix_data + "_GeneratedSample_DENSITY_X_" + x_name + "_Y_" + y_name + ".csv"; System.out.print( "\nSaving generated sample for density plot in file " + save_sample_density_plot_csv + " ..."); to_file(v_gen, save_sample_density_plot_csv, true, x_index, y_index); System.out.println(" ok."); } } System.out.println("Stopping..."); wrap.myDomain.myMemoryMonitor.stop(); } public void to_file( Vector<Example> v_gen, String nameFile, boolean save_density, int x_index, int y_index) { FileWriter f; int i; try { f = new FileWriter(nameFile); if (save_density) { f.write( (wrap.myDomain.myDS.domain_feature(x_index)).name + Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX] + (wrap.myDomain.myDS.domain_feature(y_index)).name + Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX] + "generated_density"); } else { for (i = 0; i < wrap.myDomain.myDS.number_domain_features(); i++) { f.write((wrap.myDomain.myDS.domain_feature(i)).name); if (i < wrap.myDomain.myDS.number_domain_features() - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } } f.write("\n"); for (i = 0; i < v_gen.size(); i++) if (save_density) f.write(((Example) v_gen.elementAt(i)).toStringSaveDensity(x_index, y_index) + "\n"); else f.write(((Example) v_gen.elementAt(i)).toStringSave() + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Generate.class :: Saving results error in file " + nameFile); } } public Generator_Tree from_file(Domain md) { Generator_Tree gt = new Generator_Tree(-1, null, -1); boolean in_nodes = false, in_arcs = false, skip = false; HashSet<Generator_Node> leaves = new HashSet<>(); Iterator lit; FileReader e; BufferedReader br; StringTokenizer t; int name, myParentGenerator_Node_name, myParentGenerator_Node_children_number, depth, i, j, index, feature_node_index, gt_depth = -1; double p_node; boolean is_leaf; double[] multi_p; Hashtable<Integer, Vector> nodes_name_to_node_and_succ_indexes_and_parent_index = new Hashtable<>(); Generator_Node gn, gn_begin_node, gn_end_node, gn_parent_node; Integer parent_index; Vector vbundle, vbundle_parent_node, vbundle_begin_node, vbundle_end_node; Vector<Vector> arc_list_with_arcs_and_nodes_names = new Vector<>(); Vector current_arc_and_nodes_names; int begin_node_name, end_node_name, feature_arc_index; Integer ibegin_node_name, iend_node_name, inode_name, iparent_name; FeaturePlus fga; Generator_Arc ga; Feature ff; Vector<String> modalities; String fname1, fname2, ftype, dum, n, dumname; double dmin, dmax; Enumeration enu; Vector<Integer> vsucc; Vector<Double> vmulti_p; System.out.print("Loading generator at " + generator_file + "... "); try { e = new FileReader(generator_file); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, Dataset.KEY_COMMENT.length()).equals(Dataset.KEY_COMMENT)))) { t = new StringTokenizer(dum, Dataset.KEY_SEPARATION_STRING[Generate.SEPARATION_INDEX]); n = t.nextToken(); if (n.equals(Generate.KEY_NODES)) { in_nodes = true; in_arcs = false; skip = true; } else if (n.equals(Generate.KEY_ARCS)) { in_arcs = true; in_nodes = false; skip = true; } if ((!skip) && ((in_nodes) || (in_arcs))) { if ((in_nodes) && (in_arcs)) Dataset.perror("Generate.java :: generator file mixed up"); if (in_nodes) { name = Integer.parseInt(n); n = t.nextToken(); myParentGenerator_Node_name = Integer.parseInt(n); n = t.nextToken(); myParentGenerator_Node_children_number = Integer.parseInt(n); n = t.nextToken(); depth = Integer.parseInt(n); if ((gt_depth == -1) || (depth > gt_depth)) gt_depth = depth; n = t.nextToken(); p_node = Double.parseDouble(n); n = t.nextToken(); is_leaf = Boolean.parseBoolean(n); multi_p = null; vsucc = null; vmulti_p = null; feature_node_index = -1; if (!is_leaf) { n = t.nextToken(); feature_node_index = Integer.parseInt(n); dumname = t.nextToken(); // not used vsucc = new Vector<>(); vmulti_p = new Vector<>(); while (t.hasMoreTokens()) { n = t.nextToken(); vmulti_p.addElement(new Double(Double.parseDouble(n))); n = t.nextToken(); vsucc.addElement(new Integer(Integer.parseInt(n))); } multi_p = new double[vmulti_p.size()]; for (i = 0; i < multi_p.length; i++) multi_p[i] = ((Double) vmulti_p.elementAt(i)).doubleValue(); } gn = new Generator_Node(gt, null, myParentGenerator_Node_children_number); if (name == 1) gt.root = gn; gn.name = name; gn.depth = depth; gn.p_node = p_node; gn.is_leaf = is_leaf; gn.multi_p = multi_p; if (!is_leaf) { gn.feature_node_index = feature_node_index; gn.children_arcs = new Generator_Arc[multi_p.length]; } else { gn.children_arcs = null; leaves.add(gn); } parent_index = new Integer(myParentGenerator_Node_name); vbundle = new Vector(); vbundle.addElement(gn); vbundle.addElement(vsucc); vbundle.addElement(parent_index); nodes_name_to_node_and_succ_indexes_and_parent_index.put(new Integer(name), vbundle); } if (in_arcs) { begin_node_name = Integer.parseInt(n); n = t.nextToken(); end_node_name = Integer.parseInt(n); n = t.nextToken(); feature_arc_index = Integer.parseInt(n); fname1 = t.nextToken(); fname2 = t.nextToken(); if (!fname1.equals(fname2)) Dataset.perror("Generate.java :: feature names " + fname1 + " != " + fname2); ftype = t.nextToken(); modalities = null; dmin = dmax = -1.0; if (Feature.IS_NOMINAL(ftype)) { modalities = new Vector<>(); while (t.hasMoreTokens()) modalities.addElement(new String(t.nextToken())); } else { n = t.nextToken(); dmin = Double.parseDouble(n); n = t.nextToken(); dmax = Double.parseDouble(n); } ff = new Feature(fname1, ftype, modalities, dmin, dmax, false); fga = new FeaturePlus(ff, feature_arc_index); current_arc_and_nodes_names = new Vector(); current_arc_and_nodes_names.addElement(fga); current_arc_and_nodes_names.addElement(new Integer(begin_node_name)); current_arc_and_nodes_names.addElement(new Integer(end_node_name)); arc_list_with_arcs_and_nodes_names.addElement(current_arc_and_nodes_names); } } else if (skip) skip = false; } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + generator_file + " resource file --- Check the access to file"); System.exit(0); } System.out.print("ok .\nFilling nodes' parents... "); // fill parents enu = nodes_name_to_node_and_succ_indexes_and_parent_index.keys(); while (enu.hasMoreElements()) { inode_name = (Integer) enu.nextElement(); vbundle = nodes_name_to_node_and_succ_indexes_and_parent_index.get(inode_name); gn = (Generator_Node) vbundle.elementAt(0); iparent_name = (Integer) vbundle.elementAt(2); if (iparent_name.intValue() != -1) { vbundle_parent_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(iparent_name); gn_parent_node = (Generator_Node) vbundle_parent_node.elementAt(0); gn.myParentGenerator_Node = gn_parent_node; } } System.out.print("ok .\nFilling arcs... "); // includes arcs in nodes for (i = 0; i < arc_list_with_arcs_and_nodes_names.size(); i++) { current_arc_and_nodes_names = (Vector) arc_list_with_arcs_and_nodes_names.elementAt(i); fga = (FeaturePlus) current_arc_and_nodes_names.elementAt(0); ibegin_node_name = (Integer) current_arc_and_nodes_names.elementAt(1); iend_node_name = (Integer) current_arc_and_nodes_names.elementAt(2); vbundle_begin_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(ibegin_node_name); gn_begin_node = (Generator_Node) vbundle_begin_node.elementAt(0); vsucc = (Vector) vbundle_begin_node.elementAt(1); vbundle_end_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(iend_node_name); gn_end_node = (Generator_Node) vbundle_end_node.elementAt(0); ga = new Generator_Arc(gn_begin_node, gn_end_node, fga.feat, fga.feat_arc_index, i); // arc now complete j = 0; index = -1; do { if (((Integer) vsucc.elementAt(j)).equals(iend_node_name)) index = j; j++; } while ((index == -1) && (j < vsucc.size())); if (index == -1) Dataset.perror( "Generate.java :: index of node # " + iend_node_name + " not found at arc #" + i); gn_begin_node.children_arcs[index] = ga; } // finishing gt.leaves = leaves; gt.depth = gt_depth; gt.number_nodes = nodes_name_to_node_and_succ_indexes_and_parent_index.size(); gt.myBoost = new Boost(wrap.myDomain); lit = leaves.iterator(); while (lit.hasNext()) { gn = (Generator_Node) lit.next(); gn.compute_all_features_domain(); } if ((x_name != null) && (!x_name.equals(""))) { i = 0; while ((i < wrap.myDomain.myDS.number_domain_features()) && (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(x_name))) i++; if (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(x_name)) Dataset.perror("Generate.class :: no feature named " + x_name + " in dataset"); x_index = i; } if ((y_name != null) && (!y_name.equals(""))) { i = 0; while ((i < wrap.myDomain.myDS.number_domain_features()) && (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(y_name))) i++; if (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(y_name)) Dataset.perror("Generate.class :: no feature named " + y_name + " in dataset"); y_index = i; } System.out.print("ok.\n"); return gt; } }
google-research/google-research
generative_trees/src/Generate.java
5,804
// Help & example run: 'java Generate --help' "
line_comment
nl
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 // class to generate data only import java.io.*; import java.util.*; class FeaturePlus { Feature feat; int feat_arc_index; FeaturePlus(Feature f, int fai) { feat = f; feat_arc_index = fai; } } class Generate implements Debuggable { public static Random R = new Random(); public static int SEPARATION_INDEX = 0; public static String KEY_HELP = "--help", KEY_GENERATOR_LINK = "-L", KEY_NUMBER_EXAMPLES = "-N", KEY_DIRECTORY = "-D", KEY_PREFIX = "-P", KEY_X = "-X", KEY_Y = "-Y", SEP = "/", KEY_FORCE_INTEGER_CODING = "-F", KEY_UNKNOWN_VALUE_CODING = "-U"; public static String KEY_NODES = "@NODES", KEY_ARCS = "@ARCS"; String generator_file, x_name, y_name, statistics_experiment, directory_data, prefix_data, generator_name, unknown_v_coding; boolean force_int_coding; int number_ex, x_index, y_index; Wrapper wrap; Generate( String xn, String yn, String dir, String pref, String gen_name, boolean force_int_coding, String unknown_v_coding) { statistics_experiment = null; x_name = xn; y_name = yn; directory_data = dir; prefix_data = pref; generator_name = gen_name; generator_file = null; this.force_int_coding = force_int_coding; if (unknown_v_coding.equals("")) this.unknown_v_coding = "-1"; else this.unknown_v_coding = unknown_v_coding; wrap = null; x_index = y_index = -1; } public static String help() { String ret = ""; ret += KEY_HELP + " : example command line\n\n"; ret += "java -Xmx10000m Generate -D Datasets/generate/ -P open_policing_hartford -U NA -F true -N" + " 1000 -L example-generator_open_policing_hartford.csv\n\n"; ret += KEY_DIRECTORY + " (String) :: mandatory -- directory where to find the resource below\n"; ret += KEY_PREFIX + " (String) :: mandatory -- prefix of the domain (the .csv datafile must be at" + " Datasets/generate/open_policing_hartford.csv)\n"; ret += KEY_UNKNOWN_VALUE_CODING + " (String) :: optional -- representation of 'unknown' value in dataset -- default:" + " \"-1\"\n"; ret += KEY_FORCE_INTEGER_CODING + " (boolean) :: optional -- if true, recognizes integer variables and codes them as" + " such (otherwise, codes them as doubles) -- default: false\n"; ret += KEY_GENERATOR_LINK + " (String) :: mandatory -- file containing the generator to be used (the file must be" + " in directory Datasets/generate/open_policing_hartford/)\n"; ret += KEY_NUMBER_EXAMPLES + " (integer) :: optional -- #examples to be generated (the file name will be at the" + " same location as generator, with name ending in '_GeneratedSample.csv'; if" + " unspecified, just displays generator)\n"; ret += KEY_X + " (String) :: optional -- variable name in x value for xy density plot of generated" + " data\n"; ret += KEY_Y + " (String) :: optional -- variable name in y value for xy density plot of generated" + " data\n"; return ret; } public static void main(String[] arg) { int i; String generator_n = ""; int number_ex = -1; boolean kF = false; String kD = "", kP = "", kU = "", xn = null, yn = null; System.out.println(""); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); System.out.println( "// Companion code to ICML'22 paper \"Generative Trees: Adversarial and Copycat\", by" + " Richard Nock and Mathieu Guillame-Bert //"); System.out.println( "// (generating examples from a generative tree; to *train* a generative tree, try 'java" + " Wrapper --help') //"); if (arg.length == 0) { System.out.println("// *No parameters*. Run 'java Generate --help' for more"); System.exit(0); } System.out.println( "// Help &<SUF> + " //"); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); for (i = 0; i < arg.length; i++) { if (arg[i].equals(KEY_HELP)) { Dataset.perror(help()); } else if (arg[i].equals(KEY_GENERATOR_LINK)) { generator_n = arg[i + 1]; } else if (arg[i].equals(KEY_DIRECTORY)) { kD = arg[i + 1]; } else if (arg[i].equals(KEY_PREFIX)) { kP = arg[i + 1]; } else if (arg[i].equals(KEY_UNKNOWN_VALUE_CODING)) { kU = arg[i + 1]; } else if (arg[i].equals(KEY_FORCE_INTEGER_CODING)) { kF = Boolean.parseBoolean(arg[i + 1]); } else if (arg[i].equals(KEY_NUMBER_EXAMPLES)) { number_ex = Integer.parseInt(arg[i + 1]); } else if (arg[i].equals(KEY_X)) { xn = new String(arg[i + 1]); } else if (arg[i].equals(KEY_Y)) { yn = new String(arg[i + 1]); } } if (generator_n.equals("")) Dataset.perror("Generate.class :: no sample to generate, check parameters"); if (kD.equals("")) Dataset.perror("Generate.class :: no directory, check parameters"); if (kP.equals("")) Dataset.perror("Generate.class :: no prefix, check parameters"); if (number_ex <= 0) Dataset.warning("Experiment.class :: no example generation"); Generate ee = new Generate(xn, yn, kD, kP, generator_n, kF, kU); ee.go(number_ex); System.out.println("\nBibTex:"); System.out.println("@inproceedings{ngbGT,"); System.out.println(" title={Generative Trees: Adversarial and Copycat},"); System.out.println(" author={R. Nock and M. Guillame-Bert},"); System.out.println(" booktitle={39$^{~th}$ International Conference on Machine Learning},"); System.out.println(" year={2022}"); System.out.println("}\n"); } public void go(int nex) { number_ex = nex; wrap = new Wrapper(); wrap.force_integer_coding = force_int_coding; Unknown_Feature_Value.S_UNKNOWN = unknown_v_coding; wrap.path_and_name_of_domain_dataset = directory_data + prefix_data + SEP + prefix_data + ".csv"; wrap.myDomain = new Domain(wrap); generator_file = directory_data + prefix_data + SEP + generator_name; System.out.println("Datafile at " + wrap.path_and_name_of_domain_dataset); System.out.println("Generator at " + generator_file); Generator_Tree gt = from_file(wrap.myDomain); System.out.println("GT loaded:"); System.out.println(gt); if (number_ex > 0) { System.out.print("\nGenerating " + number_ex + " examples... "); Vector<Example> v_gen; if (((x_name != null) && (!x_name.equals(""))) && ((y_name != null) && (!y_name.equals("")))) v_gen = gt.generate_sample_with_density(number_ex); else v_gen = gt.generate_sample(number_ex); String save_sample_csv = directory_data + prefix_data + SEP + prefix_data + "_GeneratedSample.csv"; String save_sample_density_plot_csv; System.out.print("ok.\nSaving generated sample in file " + save_sample_csv + " ..."); to_file(v_gen, save_sample_csv, false, -1, -1); System.out.println(" ok."); if ((x_name != null) && (y_name != null)) { save_sample_density_plot_csv = directory_data + prefix_data + SEP + prefix_data + "_GeneratedSample_DENSITY_X_" + x_name + "_Y_" + y_name + ".csv"; System.out.print( "\nSaving generated sample for density plot in file " + save_sample_density_plot_csv + " ..."); to_file(v_gen, save_sample_density_plot_csv, true, x_index, y_index); System.out.println(" ok."); } } System.out.println("Stopping..."); wrap.myDomain.myMemoryMonitor.stop(); } public void to_file( Vector<Example> v_gen, String nameFile, boolean save_density, int x_index, int y_index) { FileWriter f; int i; try { f = new FileWriter(nameFile); if (save_density) { f.write( (wrap.myDomain.myDS.domain_feature(x_index)).name + Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX] + (wrap.myDomain.myDS.domain_feature(y_index)).name + Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX] + "generated_density"); } else { for (i = 0; i < wrap.myDomain.myDS.number_domain_features(); i++) { f.write((wrap.myDomain.myDS.domain_feature(i)).name); if (i < wrap.myDomain.myDS.number_domain_features() - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } } f.write("\n"); for (i = 0; i < v_gen.size(); i++) if (save_density) f.write(((Example) v_gen.elementAt(i)).toStringSaveDensity(x_index, y_index) + "\n"); else f.write(((Example) v_gen.elementAt(i)).toStringSave() + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Generate.class :: Saving results error in file " + nameFile); } } public Generator_Tree from_file(Domain md) { Generator_Tree gt = new Generator_Tree(-1, null, -1); boolean in_nodes = false, in_arcs = false, skip = false; HashSet<Generator_Node> leaves = new HashSet<>(); Iterator lit; FileReader e; BufferedReader br; StringTokenizer t; int name, myParentGenerator_Node_name, myParentGenerator_Node_children_number, depth, i, j, index, feature_node_index, gt_depth = -1; double p_node; boolean is_leaf; double[] multi_p; Hashtable<Integer, Vector> nodes_name_to_node_and_succ_indexes_and_parent_index = new Hashtable<>(); Generator_Node gn, gn_begin_node, gn_end_node, gn_parent_node; Integer parent_index; Vector vbundle, vbundle_parent_node, vbundle_begin_node, vbundle_end_node; Vector<Vector> arc_list_with_arcs_and_nodes_names = new Vector<>(); Vector current_arc_and_nodes_names; int begin_node_name, end_node_name, feature_arc_index; Integer ibegin_node_name, iend_node_name, inode_name, iparent_name; FeaturePlus fga; Generator_Arc ga; Feature ff; Vector<String> modalities; String fname1, fname2, ftype, dum, n, dumname; double dmin, dmax; Enumeration enu; Vector<Integer> vsucc; Vector<Double> vmulti_p; System.out.print("Loading generator at " + generator_file + "... "); try { e = new FileReader(generator_file); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, Dataset.KEY_COMMENT.length()).equals(Dataset.KEY_COMMENT)))) { t = new StringTokenizer(dum, Dataset.KEY_SEPARATION_STRING[Generate.SEPARATION_INDEX]); n = t.nextToken(); if (n.equals(Generate.KEY_NODES)) { in_nodes = true; in_arcs = false; skip = true; } else if (n.equals(Generate.KEY_ARCS)) { in_arcs = true; in_nodes = false; skip = true; } if ((!skip) && ((in_nodes) || (in_arcs))) { if ((in_nodes) && (in_arcs)) Dataset.perror("Generate.java :: generator file mixed up"); if (in_nodes) { name = Integer.parseInt(n); n = t.nextToken(); myParentGenerator_Node_name = Integer.parseInt(n); n = t.nextToken(); myParentGenerator_Node_children_number = Integer.parseInt(n); n = t.nextToken(); depth = Integer.parseInt(n); if ((gt_depth == -1) || (depth > gt_depth)) gt_depth = depth; n = t.nextToken(); p_node = Double.parseDouble(n); n = t.nextToken(); is_leaf = Boolean.parseBoolean(n); multi_p = null; vsucc = null; vmulti_p = null; feature_node_index = -1; if (!is_leaf) { n = t.nextToken(); feature_node_index = Integer.parseInt(n); dumname = t.nextToken(); // not used vsucc = new Vector<>(); vmulti_p = new Vector<>(); while (t.hasMoreTokens()) { n = t.nextToken(); vmulti_p.addElement(new Double(Double.parseDouble(n))); n = t.nextToken(); vsucc.addElement(new Integer(Integer.parseInt(n))); } multi_p = new double[vmulti_p.size()]; for (i = 0; i < multi_p.length; i++) multi_p[i] = ((Double) vmulti_p.elementAt(i)).doubleValue(); } gn = new Generator_Node(gt, null, myParentGenerator_Node_children_number); if (name == 1) gt.root = gn; gn.name = name; gn.depth = depth; gn.p_node = p_node; gn.is_leaf = is_leaf; gn.multi_p = multi_p; if (!is_leaf) { gn.feature_node_index = feature_node_index; gn.children_arcs = new Generator_Arc[multi_p.length]; } else { gn.children_arcs = null; leaves.add(gn); } parent_index = new Integer(myParentGenerator_Node_name); vbundle = new Vector(); vbundle.addElement(gn); vbundle.addElement(vsucc); vbundle.addElement(parent_index); nodes_name_to_node_and_succ_indexes_and_parent_index.put(new Integer(name), vbundle); } if (in_arcs) { begin_node_name = Integer.parseInt(n); n = t.nextToken(); end_node_name = Integer.parseInt(n); n = t.nextToken(); feature_arc_index = Integer.parseInt(n); fname1 = t.nextToken(); fname2 = t.nextToken(); if (!fname1.equals(fname2)) Dataset.perror("Generate.java :: feature names " + fname1 + " != " + fname2); ftype = t.nextToken(); modalities = null; dmin = dmax = -1.0; if (Feature.IS_NOMINAL(ftype)) { modalities = new Vector<>(); while (t.hasMoreTokens()) modalities.addElement(new String(t.nextToken())); } else { n = t.nextToken(); dmin = Double.parseDouble(n); n = t.nextToken(); dmax = Double.parseDouble(n); } ff = new Feature(fname1, ftype, modalities, dmin, dmax, false); fga = new FeaturePlus(ff, feature_arc_index); current_arc_and_nodes_names = new Vector(); current_arc_and_nodes_names.addElement(fga); current_arc_and_nodes_names.addElement(new Integer(begin_node_name)); current_arc_and_nodes_names.addElement(new Integer(end_node_name)); arc_list_with_arcs_and_nodes_names.addElement(current_arc_and_nodes_names); } } else if (skip) skip = false; } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + generator_file + " resource file --- Check the access to file"); System.exit(0); } System.out.print("ok .\nFilling nodes' parents... "); // fill parents enu = nodes_name_to_node_and_succ_indexes_and_parent_index.keys(); while (enu.hasMoreElements()) { inode_name = (Integer) enu.nextElement(); vbundle = nodes_name_to_node_and_succ_indexes_and_parent_index.get(inode_name); gn = (Generator_Node) vbundle.elementAt(0); iparent_name = (Integer) vbundle.elementAt(2); if (iparent_name.intValue() != -1) { vbundle_parent_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(iparent_name); gn_parent_node = (Generator_Node) vbundle_parent_node.elementAt(0); gn.myParentGenerator_Node = gn_parent_node; } } System.out.print("ok .\nFilling arcs... "); // includes arcs in nodes for (i = 0; i < arc_list_with_arcs_and_nodes_names.size(); i++) { current_arc_and_nodes_names = (Vector) arc_list_with_arcs_and_nodes_names.elementAt(i); fga = (FeaturePlus) current_arc_and_nodes_names.elementAt(0); ibegin_node_name = (Integer) current_arc_and_nodes_names.elementAt(1); iend_node_name = (Integer) current_arc_and_nodes_names.elementAt(2); vbundle_begin_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(ibegin_node_name); gn_begin_node = (Generator_Node) vbundle_begin_node.elementAt(0); vsucc = (Vector) vbundle_begin_node.elementAt(1); vbundle_end_node = nodes_name_to_node_and_succ_indexes_and_parent_index.get(iend_node_name); gn_end_node = (Generator_Node) vbundle_end_node.elementAt(0); ga = new Generator_Arc(gn_begin_node, gn_end_node, fga.feat, fga.feat_arc_index, i); // arc now complete j = 0; index = -1; do { if (((Integer) vsucc.elementAt(j)).equals(iend_node_name)) index = j; j++; } while ((index == -1) && (j < vsucc.size())); if (index == -1) Dataset.perror( "Generate.java :: index of node # " + iend_node_name + " not found at arc #" + i); gn_begin_node.children_arcs[index] = ga; } // finishing gt.leaves = leaves; gt.depth = gt_depth; gt.number_nodes = nodes_name_to_node_and_succ_indexes_and_parent_index.size(); gt.myBoost = new Boost(wrap.myDomain); lit = leaves.iterator(); while (lit.hasNext()) { gn = (Generator_Node) lit.next(); gn.compute_all_features_domain(); } if ((x_name != null) && (!x_name.equals(""))) { i = 0; while ((i < wrap.myDomain.myDS.number_domain_features()) && (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(x_name))) i++; if (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(x_name)) Dataset.perror("Generate.class :: no feature named " + x_name + " in dataset"); x_index = i; } if ((y_name != null) && (!y_name.equals(""))) { i = 0; while ((i < wrap.myDomain.myDS.number_domain_features()) && (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(y_name))) i++; if (!(wrap.myDomain.myDS.domain_feature(i)).name.equals(y_name)) Dataset.perror("Generate.class :: no feature named " + y_name + " in dataset"); y_index = i; } System.out.print("ok.\n"); return gt; } }
454_14
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 import java.io.*; import java.util.*; class Wrapper implements Debuggable { public static String DATASET = "--dataset=", DATASET_SPEC = "--dataset_spec=", NUM_SAMPLES = "--num_samples=", WORK_DIR = "--work_dir=", OUTPUT_SAMPLES = "--output_samples=", OUTPUT_STATS = "--output_stats=", X = "--x=", Y = "--y=", FLAGS = "--flags", HELP = "--help", IMPUTE_MISSING = "--impute_missing="; public static String[] ALL_FLAGS = { "iterations", "unknown_value_coding", "force_integer_coding", "number_bins_for_histograms", "force_binary_coding", "faster_induction", "copycat_local_generation" }; // all flag names recognized in command line in --flags = {"name" : value, ...} // nodes_in_gt: integer = number of nodes in the GT learned // unknown_value_coding: String = enforces an "unknown value" different from default // force_integer_coding: boolean = if true, enforce integer coding of observation variables // recognizable as integers ("cleaner" GT) // number_bins_for_histograms = integer, number of bins to compute the GT histograms of marginals // at the end public static int ALL_FLAGS_INDEX_ITERATIONS = 0, ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING = 1, ALL_FLAGS_FORCE_INTEGER_CODING = 2, ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS = 3, ALL_FLAGS_FORCE_BINARY_CODING = 4, ALL_FLAGS_FASTER_INDUCTION = 5, ALL_FLAGS_COPYCAT_LOCAL_GENERATION = 6; public static String[] DATASET_TOKENS = { "\"name\":", "\"path\":", "\"label\":", "\"task\":" }; // spec_name, spec_path, spec_label, spec_task public static String PREFIX_GENERATOR = "generator_"; public String path_and_name_of_domain_dataset, path_to_generated_samples, working_directory, blueprint_save_name, spec_name, prefix_domain, spec_path, spec_label, spec_task, x_name, y_name, output_stats_file, output_stats_directory, generator_filename, densityplot_filename; // spec_name = prefix name public String[] flags_values; int size_generated, number_iterations; // was nums int index_x_name, index_y_name; Algorithm myAlgos; Domain myDomain; boolean force_integer_coding = false, force_binary_coding = true, faster_induction = false, impute_missing = false, has_missing_values, copycat_local_generation = true; long loading_time, gt_computation_time, marginal_computation_time, saving_generator_time, saving_stats_time, generate_examples_time, saving_generated_sample_time, saving_density_plot_generated_sample_time, imputation_time; Wrapper() { flags_values = new String[ALL_FLAGS.length]; size_generated = number_iterations = -1; index_x_name = index_y_name = -1; densityplot_filename = null; x_name = y_name = null; path_and_name_of_domain_dataset = spec_path = null; loading_time = gt_computation_time = marginal_computation_time = saving_generator_time = saving_stats_time = generate_examples_time = saving_generated_sample_time = saving_density_plot_generated_sample_time = 0; has_missing_values = false; } public static String help() { String ret = ""; ret += "Example run\n"; ret += "Java Wrapper --dataset=${ANYDIR}/Datasets/iris/iris.csv\n"; ret += " '--dataset_spec={\"name\": \"iris\", \"path\":" + " \"${ANYDIR}/Datasets/iris/iris.csv\", \"label\": \"class\", \"task\":" + " \"BINARY_CLASSIFICATION\"}'\n"; ret += " --num_samples=10000 \n"; ret += " --work_dir=${ANYDIR}/Datasets/iris/working_dir \n"; ret += " " + " --output_samples=${ANYDIR}/Datasets/iris/output_samples/iris_gt_generated.csv\n"; ret += " --output_stats=${ANYDIR}/Datasets/iris/results/generated_examples.stats \n"; ret += " --x=Sepal.Length --y=Sepal.Width \n"; ret += " '--flags={\"iterations\" : \"10\", \"force_integer_coding\" : \"true\"," + " \"force_binary_coding\" : \"true\", \"faster_induction\" : \"true\"," + " \"unknown_value_coding\" : \"?\", \"number_bins_for_histograms\" : \"11\"}'\n"; ret += " --impute_missing=true\n\n"; ret += " --dataset: path to access the.csv data file containing variable names in first line\n"; ret += " --dataset_spec: self explanatory\n"; ret += " --num_samples: number of generated samples\n"; ret += " --work_dir: directory where the generator and density plots are saved\n"; ret += " --output_samples: generated samples filename\n"; ret += " --output_stats: file to store all data related to run (execution times, GT marginals" + " histograms, GT tree node stats, etc)\n"; ret += " --x --y: (optional) variables used to save a 2D density plot" + " (x,y,denxity_value_at_(x,y))\n"; ret += " --flags: flags...\n"; ret += " iterations (mandatory): integer; number of splits in the GT; final number of" + " nodes = 2 * iteration + 1\n"; ret += " force_integer_coding (optional): boolean; if true, recognizes integer variables" + " and codes them as such (otherwise, codes them as doubles) -- default: false\n"; ret += " force_binary_coding (optional): boolean; if true, recognizes 0/1/unknown" + " variables and codes them as nominal, otherwise treat them as integers or doubles --" + " default: true\n"; ret += " faster_induction (optional): boolean; if true, optimises training by sampling DT" + " splits if too many (i.e. more than " + Discriminator_Tree.MAX_SPLITS_BEFORE_RANDOMISATION + ") -- default: false\n"; ret += " unknown_value_coding (optional): String; representation of 'unknown' value in" + " dataset -- default: \"-1\"\n"; ret += " number_bins_for_histograms (optional): integer; number of bins for non-nominal" + " variables to store the learned GT marginals -- default: 19\n"; ret += " copycat_local_generation (optional): boolean; if true, when copycat induction" + " used, after a new split in GT, example generation only replaces the affected" + " feature for the locally generated examples -- default: true\n"; ret += " --impute_missing: if true, uses the generated tree to impute the missing values in the" + " training data\n"; return ret; } public static void main(String[] arg) { int i; Wrapper w = new Wrapper(); System.out.println(""); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); System.out.println( "// Companion code to ICML'22 paper \"Generative Trees: Adversarial and Copycat\", by" + " Richard Nock and Mathieu Guillame-Bert //"); System.out.println( "// (copycat training of generative trees) " + " //"); if (arg.length == 0) { System.out.println("// *No parameters*. Run 'java Wrapper --help' for more"); System.exit(0); } System.out.println( "// Help & example run: 'java Wrapper --help' " + " //"); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); for (i = 0; i < arg.length; i++) { if (arg[i].equals(HELP)) { System.out.println(help()); System.exit(0); } w.fit_vars(arg[i]); } w.summary(); w.simple_go(); System.out.println("\nBibTex:"); System.out.println("@inproceedings{ngbGT,"); System.out.println(" title={Generative Trees: Adversarial and Copycat},"); System.out.println(" author={R. Nock and M. Guillame-Bert},"); System.out.println(" booktitle={39$^{~th}$ International Conference on Machine Learning},"); System.out.println(" year={2022}"); System.out.println("}\n"); } public void simple_go() { Algorithm.INIT(); long b, e; Vector<Example> v_gen; System.out.print("Loading stuff start... "); b = System.currentTimeMillis(); myDomain = new Domain(this); myAlgos = new Algorithm(myDomain); e = System.currentTimeMillis(); loading_time = e - b; System.out.println("Loading stuff ok (time elapsed: " + loading_time + " ms).\n"); String[] parameters = { "@MatuErr", "1.0", "COPYCAT", number_iterations + "", copycat_local_generation + "" }; Vector<String> params = new Vector<>(Arrays.asList(parameters)); myAlgos.addAlgorithm(params); System.out.print("Learning the generator... "); b = System.currentTimeMillis(); Generator_Tree gt = myAlgos.simple_go(); e = System.currentTimeMillis(); gt_computation_time = e - b; System.out.println( "ok (time elapsed: " + gt_computation_time + " ms).\n\nGenerative tree learned: " + gt); System.out.print("Computing GT marginals histograms... "); b = System.currentTimeMillis(); gt.compute_generator_histograms(); e = System.currentTimeMillis(); marginal_computation_time = e - b; System.out.println("ok (time elapsed: " + marginal_computation_time + " ms)."); System.out.print("Saving the GT... "); b = System.currentTimeMillis(); Generator_Tree.SAVE_GENERATOR_TREE(gt, working_directory + "/" + generator_filename, ""); e = System.currentTimeMillis(); saving_generator_time = e - b; System.out.println("ok (time elapsed: " + saving_generator_time + " ms)."); System.out.print("Generating " + size_generated + " examples using the GT... "); b = System.currentTimeMillis(); v_gen = gt.generate_sample_with_density(size_generated); e = System.currentTimeMillis(); generate_examples_time = e - b; System.out.println("ok (time elapsed: " + generate_examples_time + " ms)."); if ((has_missing_values) && (impute_missing)) { System.out.print("Imputing examples using the GT... "); b = System.currentTimeMillis(); impute_and_save(gt); e = System.currentTimeMillis(); imputation_time = e - b; System.out.println("ok (time elapsed: " + imputation_time + " ms)."); } System.out.print("Saving generated sample... "); b = System.currentTimeMillis(); save_sample(v_gen); e = System.currentTimeMillis(); saving_generated_sample_time = e - b; System.out.println("ok (time elapsed: " + saving_generated_sample_time + " ms)."); if ((x_name != null) && (y_name != null)) { System.out.print("Saving density plot sample... "); b = System.currentTimeMillis(); save_density_plot_sample(v_gen, index_x_name, index_y_name); e = System.currentTimeMillis(); saving_density_plot_generated_sample_time = e - b; System.out.println( "ok (time elapsed: " + saving_density_plot_generated_sample_time + " ms)."); } System.out.print("Saving stats file... "); b = System.currentTimeMillis(); save_stats(gt); e = System.currentTimeMillis(); saving_stats_time = e - b; System.out.println("ok (time elapsed: " + saving_stats_time + " ms)."); System.out.println("All finished. Stopping..."); myDomain.myMemoryMonitor.stop(); } public void save_density_plot_sample(Vector<Example> v_gen, int x, int y) { FileWriter f; int i; String nameFile = working_directory + "/" + densityplot_filename; try { f = new FileWriter(nameFile); f.write("//" + x_name + "," + y_name + ",density_value\n"); for (i = 0; i < v_gen.size(); i++) f.write( ((Example) v_gen.elementAt(i)).toStringSaveDensity(index_x_name, index_y_name) + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void save_sample(Vector<Example> v_gen) { FileWriter f; int i; String nameFile = path_to_generated_samples + "/" + blueprint_save_name; try { f = new FileWriter(nameFile); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write(myDomain.myDS.features_names_from_file[i]); if (i < myDomain.myDS.features_names_from_file.length - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } f.write("\n"); for (i = 0; i < v_gen.size(); i++) f.write(((Example) v_gen.elementAt(i)).toStringSave() + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void impute_and_save(Generator_Tree gt) { FileWriter f; int i, j; String nameFile = working_directory + "/" + spec_name + "_imputed.csv"; Example ee, ee_cop; try { f = new FileWriter(nameFile); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write(myDomain.myDS.features_names_from_file[i]); if (i < myDomain.myDS.features_names_from_file.length - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } f.write("\n"); for (i = 0; i < myDomain.myDS.number_examples_total_from_file; i++) { if (i % (myDomain.myDS.number_examples_total_from_file / 10) == 0) System.out.print((i / (myDomain.myDS.number_examples_total_from_file / 10)) * 10 + "% "); ee = (Example) myDomain.myDS.examples_from_file.elementAt(i); ee_cop = Example.copyOf(ee); if (ee.contains_unknown_values()) { gt.impute_all_values_from_one_leaf(ee_cop); } f.write(ee_cop.toStringSave() + "\n"); } f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void save_stats(Generator_Tree gt) { int i; FileWriter f = null; int[] node_counts = new int[myDomain.myDS.features_names_from_file.length]; String output_stats_additional = output_stats_file + "_more.txt"; long time_gt_plus_generation = gt_computation_time + generate_examples_time; long time_gt_plus_imputation = -1; if ((has_missing_values) && (impute_missing)) time_gt_plus_imputation = gt_computation_time + imputation_time; try { f = new FileWriter(output_stats_file); f.write("{\n"); f.write( " \"running_time_seconds\": " + DF8.format(((double) gt_computation_time + generate_examples_time) / 1000) + ",\n"); f.write(" \"gt_number_nodes\": " + gt.number_nodes + ",\n"); f.write(" \"gt_depth\": " + gt.depth + ",\n"); f.write( " \"running_time_gt_training_plus_exemple_generation\": " + DF8.format(((double) time_gt_plus_generation / 1000)) + ",\n"); if ((has_missing_values) && (impute_missing)) f.write( " \"running_time_gt_training_plus_imputation\": " + DF8.format(((double) time_gt_plus_imputation / 1000)) + "\n"); f.write("}\n"); f.close(); } catch (IOException e) { Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_file); } try { f = new FileWriter(output_stats_additional); f.write("// flag values used: "); for (i = 0; i < flags_values.length; i++) f.write(" [" + ALL_FLAGS[i] + ":" + flags_values[i] + "] "); f.write("\n\n"); f.write("// Time to learn the generator: " + gt_computation_time + " ms.\n"); f.write("// Time to generate sample: " + generate_examples_time + " ms.\n"); // saves the gt histograms for comparison f.write("\n// GT Histograms of marginals\n"); for (i = 0; i < gt.gt_histograms.size(); i++) { f.write((gt.gt_histograms.elementAt(i)).toStringSave()); f.write("//\n"); } gt.root.recursive_fill_node_counts(node_counts, myDomain.myDS.features_names_from_file); f.write("\n// GT node counts per feature name\n"); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write("// " + myDomain.myDS.features_names_from_file[i] + " : " + node_counts[i] + "\n"); } f.close(); } catch (IOException e) { Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_additional); } } public void summary() { int i; System.out.println("\nRunning copycat generator training with the following inputs:"); System.out.println(" * dataset path to train generator:" + path_and_name_of_domain_dataset); System.out.println(" * working directory:" + working_directory); System.out.println( " * generated samples (" + size_generated + " examples) stored in directory " + path_to_generated_samples + " with filename " + blueprint_save_name); System.out.println( " * generator (gt) stored in working directory with filename " + generator_filename); System.out.println(" * stats file at " + output_stats_file); if (spec_path == null) Dataset.warning(" No path information in --dataset_spec"); else if (!path_and_name_of_domain_dataset.equals(spec_path)) Dataset.warning(" Non identical information in --dataset_spec path vs --dataset\n"); if (impute_missing) System.out.println( " * imputed sample saved at filename " + working_directory + "/" + spec_name + "_imputed.csv"); if ((x_name != null) && (y_name != null) && (!x_name.equals("")) && (!y_name.equals(""))) { densityplot_filename = blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.')) + "_2DDensity_plot_X_" + x_name + "_Y_" + y_name + blueprint_save_name.substring( blueprint_save_name.lastIndexOf('.'), blueprint_save_name.length()); System.out.println( " * 2D density plot for (" + x_name + "," + y_name + ") stored in working directory with filename " + densityplot_filename); } System.out.print(" * flags (non null): "); for (i = 0; i < flags_values.length; i++) if (flags_values[i] != null) System.out.print("[" + ALL_FLAGS[i] + ":" + flags_values[i] + "] "); System.out.println(""); if (flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING] != null) Unknown_Feature_Value.S_UNKNOWN = flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING]; if (flags_values[ALL_FLAGS_FORCE_INTEGER_CODING] != null) force_integer_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_INTEGER_CODING]); if (flags_values[ALL_FLAGS_FORCE_BINARY_CODING] != null) force_binary_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_BINARY_CODING]); if (flags_values[ALL_FLAGS_FASTER_INDUCTION] != null) faster_induction = Boolean.parseBoolean(flags_values[ALL_FLAGS_FASTER_INDUCTION]); if (flags_values[ALL_FLAGS_INDEX_ITERATIONS] != null) number_iterations = Integer.parseInt(flags_values[ALL_FLAGS_INDEX_ITERATIONS]); if (flags_values[ALL_FLAGS_COPYCAT_LOCAL_GENERATION] != null) copycat_local_generation = Boolean.parseBoolean(flags_values[ALL_FLAGS_COPYCAT_LOCAL_GENERATION]); Boost.COPYCAT_GENERATE_WITH_WHOLE_GT = !copycat_local_generation; if (flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS] != null) { Histogram.NUMBER_CONTINUOUS_FEATURE_BINS = Integer.parseInt(flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS]); Histogram.MAX_NUMBER_INTEGER_FEATURE_BINS = Integer.parseInt(flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS]); } Dataset.NUMBER_GENERATED_EXAMPLES_DEFAULT = -1; Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS = true; Discriminator_Tree.RANDOMISE_SPLIT_FINDING_WHEN_TOO_MANY_SPLITS = faster_induction; System.out.println(""); } public void fit_vars(String s) { String dummys; if (s.contains(DATASET)) { path_and_name_of_domain_dataset = s.substring(DATASET.length(), s.length()); spec_name = path_and_name_of_domain_dataset.substring( path_and_name_of_domain_dataset.lastIndexOf('/') + 1, path_and_name_of_domain_dataset.lastIndexOf('.')); } else if (s.contains(DATASET_SPEC)) { spec_path = spec_label = spec_task = null; int i, begin_ind, end_ind; String[] values = new String[4]; int[] index_tokens = {0, 0, 0, 0}; for (i = 0; i < DATASET_TOKENS.length; i++) { if (s.indexOf(DATASET_TOKENS[i]) != s.lastIndexOf(DATASET_TOKENS[i])) Dataset.perror( "Wrapper.class :: more than one occurrence of " + DATASET_TOKENS[i] + " in string" + s); if (s.indexOf(DATASET_TOKENS[i]) == -1) Dataset.perror( "Wrapper.class :: zero occurrence of " + DATASET_TOKENS[i] + " in string" + s); else index_tokens[i] = s.indexOf(DATASET_TOKENS[i]); } for (i = 0; i < DATASET_TOKENS.length - 1; i++) if (index_tokens[i] > index_tokens[i + 1]) Dataset.perror( "Wrapper.class :: token " + DATASET_TOKENS[i] + " should appear before token " + DATASET_TOKENS[i + 1] + " in string" + s); for (i = 0; i < DATASET_TOKENS.length; i++) { begin_ind = index_tokens[i] + DATASET_TOKENS[i].length(); if (i == DATASET_TOKENS.length - 1) end_ind = s.length(); else end_ind = index_tokens[i + 1] - 1; dummys = s.substring(begin_ind, end_ind); values[i] = dummys.substring(dummys.indexOf('\"') + 1, dummys.lastIndexOf('\"')); } prefix_domain = spec_name; spec_path = values[1]; spec_label = values[2]; spec_task = values[3]; } else if (s.contains(NUM_SAMPLES)) { size_generated = Integer.parseInt(s.substring(NUM_SAMPLES.length(), s.length())); } else if (s.contains(WORK_DIR)) { working_directory = s.substring(WORK_DIR.length(), s.length()); } else if (s.contains(OUTPUT_SAMPLES)) { dummys = s.substring(OUTPUT_SAMPLES.length(), s.length()); path_to_generated_samples = dummys.substring(0, dummys.lastIndexOf('/')); blueprint_save_name = dummys.substring(dummys.lastIndexOf('/') + 1, dummys.length()); generator_filename = PREFIX_GENERATOR + blueprint_save_name; } else if (s.contains(OUTPUT_STATS)) { output_stats_file = s.substring(OUTPUT_STATS.length(), s.length()); output_stats_directory = s.substring(OUTPUT_STATS.length(), s.lastIndexOf('/')); } else if (s.contains(X)) { x_name = s.substring(X.length(), s.length()); } else if (s.contains(Y)) { y_name = s.substring(Y.length(), s.length()); } else if (s.contains(FLAGS)) { dummys = ((s.substring(FLAGS.length(), s.length())).replaceAll(" ", "")).replaceAll("=", ""); if (!dummys.substring(0, 1).equals("{")) Dataset.perror("Wrapper.class :: FLAGS flags does not begin with '{'"); if (!dummys.substring(dummys.length() - 1, dummys.length()).equals("}")) Dataset.perror("Wrapper.class :: FLAGS flags does not end with '}'"); dummys = (dummys.substring(1, dummys.length() - 1)).replace("\"", ""); int b = 0, e = -1, i; String subs, tags, vals; while (e < dummys.length()) { b = e + 1; do { e++; } while ((e < dummys.length()) && (!dummys.substring(e, e + 1).equals(","))); subs = dummys.substring(b, e); if (!subs.contains(":")) Dataset.perror("Wrapper.class :: flags string " + subs + " not of the syntax tag:value"); tags = subs.substring(0, subs.lastIndexOf(':')); vals = subs.substring(subs.lastIndexOf(':') + 1, subs.length()); i = 0; do { if (!ALL_FLAGS[i].equals(tags)) i++; } while ((i < ALL_FLAGS.length) && (!ALL_FLAGS[i].equals(tags))); if (i == ALL_FLAGS.length) Dataset.perror("Wrapper.class :: flags string " + tags + " not in authorized tags"); flags_values[i] = vals; } } else if (s.contains(IMPUTE_MISSING)) { impute_missing = Boolean.parseBoolean(s.substring(IMPUTE_MISSING.length(), s.length())); } if ((x_name != null) && (y_name != null) && (x_name.equals(y_name))) Dataset.perror( "Wrapper.class :: density plot requested on the same X and Y variable = " + x_name); } }
google-research/google-research
generative_trees/src/Wrapper.java
7,668
// Help & example run: 'java Wrapper --help' "
line_comment
nl
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 import java.io.*; import java.util.*; class Wrapper implements Debuggable { public static String DATASET = "--dataset=", DATASET_SPEC = "--dataset_spec=", NUM_SAMPLES = "--num_samples=", WORK_DIR = "--work_dir=", OUTPUT_SAMPLES = "--output_samples=", OUTPUT_STATS = "--output_stats=", X = "--x=", Y = "--y=", FLAGS = "--flags", HELP = "--help", IMPUTE_MISSING = "--impute_missing="; public static String[] ALL_FLAGS = { "iterations", "unknown_value_coding", "force_integer_coding", "number_bins_for_histograms", "force_binary_coding", "faster_induction", "copycat_local_generation" }; // all flag names recognized in command line in --flags = {"name" : value, ...} // nodes_in_gt: integer = number of nodes in the GT learned // unknown_value_coding: String = enforces an "unknown value" different from default // force_integer_coding: boolean = if true, enforce integer coding of observation variables // recognizable as integers ("cleaner" GT) // number_bins_for_histograms = integer, number of bins to compute the GT histograms of marginals // at the end public static int ALL_FLAGS_INDEX_ITERATIONS = 0, ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING = 1, ALL_FLAGS_FORCE_INTEGER_CODING = 2, ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS = 3, ALL_FLAGS_FORCE_BINARY_CODING = 4, ALL_FLAGS_FASTER_INDUCTION = 5, ALL_FLAGS_COPYCAT_LOCAL_GENERATION = 6; public static String[] DATASET_TOKENS = { "\"name\":", "\"path\":", "\"label\":", "\"task\":" }; // spec_name, spec_path, spec_label, spec_task public static String PREFIX_GENERATOR = "generator_"; public String path_and_name_of_domain_dataset, path_to_generated_samples, working_directory, blueprint_save_name, spec_name, prefix_domain, spec_path, spec_label, spec_task, x_name, y_name, output_stats_file, output_stats_directory, generator_filename, densityplot_filename; // spec_name = prefix name public String[] flags_values; int size_generated, number_iterations; // was nums int index_x_name, index_y_name; Algorithm myAlgos; Domain myDomain; boolean force_integer_coding = false, force_binary_coding = true, faster_induction = false, impute_missing = false, has_missing_values, copycat_local_generation = true; long loading_time, gt_computation_time, marginal_computation_time, saving_generator_time, saving_stats_time, generate_examples_time, saving_generated_sample_time, saving_density_plot_generated_sample_time, imputation_time; Wrapper() { flags_values = new String[ALL_FLAGS.length]; size_generated = number_iterations = -1; index_x_name = index_y_name = -1; densityplot_filename = null; x_name = y_name = null; path_and_name_of_domain_dataset = spec_path = null; loading_time = gt_computation_time = marginal_computation_time = saving_generator_time = saving_stats_time = generate_examples_time = saving_generated_sample_time = saving_density_plot_generated_sample_time = 0; has_missing_values = false; } public static String help() { String ret = ""; ret += "Example run\n"; ret += "Java Wrapper --dataset=${ANYDIR}/Datasets/iris/iris.csv\n"; ret += " '--dataset_spec={\"name\": \"iris\", \"path\":" + " \"${ANYDIR}/Datasets/iris/iris.csv\", \"label\": \"class\", \"task\":" + " \"BINARY_CLASSIFICATION\"}'\n"; ret += " --num_samples=10000 \n"; ret += " --work_dir=${ANYDIR}/Datasets/iris/working_dir \n"; ret += " " + " --output_samples=${ANYDIR}/Datasets/iris/output_samples/iris_gt_generated.csv\n"; ret += " --output_stats=${ANYDIR}/Datasets/iris/results/generated_examples.stats \n"; ret += " --x=Sepal.Length --y=Sepal.Width \n"; ret += " '--flags={\"iterations\" : \"10\", \"force_integer_coding\" : \"true\"," + " \"force_binary_coding\" : \"true\", \"faster_induction\" : \"true\"," + " \"unknown_value_coding\" : \"?\", \"number_bins_for_histograms\" : \"11\"}'\n"; ret += " --impute_missing=true\n\n"; ret += " --dataset: path to access the.csv data file containing variable names in first line\n"; ret += " --dataset_spec: self explanatory\n"; ret += " --num_samples: number of generated samples\n"; ret += " --work_dir: directory where the generator and density plots are saved\n"; ret += " --output_samples: generated samples filename\n"; ret += " --output_stats: file to store all data related to run (execution times, GT marginals" + " histograms, GT tree node stats, etc)\n"; ret += " --x --y: (optional) variables used to save a 2D density plot" + " (x,y,denxity_value_at_(x,y))\n"; ret += " --flags: flags...\n"; ret += " iterations (mandatory): integer; number of splits in the GT; final number of" + " nodes = 2 * iteration + 1\n"; ret += " force_integer_coding (optional): boolean; if true, recognizes integer variables" + " and codes them as such (otherwise, codes them as doubles) -- default: false\n"; ret += " force_binary_coding (optional): boolean; if true, recognizes 0/1/unknown" + " variables and codes them as nominal, otherwise treat them as integers or doubles --" + " default: true\n"; ret += " faster_induction (optional): boolean; if true, optimises training by sampling DT" + " splits if too many (i.e. more than " + Discriminator_Tree.MAX_SPLITS_BEFORE_RANDOMISATION + ") -- default: false\n"; ret += " unknown_value_coding (optional): String; representation of 'unknown' value in" + " dataset -- default: \"-1\"\n"; ret += " number_bins_for_histograms (optional): integer; number of bins for non-nominal" + " variables to store the learned GT marginals -- default: 19\n"; ret += " copycat_local_generation (optional): boolean; if true, when copycat induction" + " used, after a new split in GT, example generation only replaces the affected" + " feature for the locally generated examples -- default: true\n"; ret += " --impute_missing: if true, uses the generated tree to impute the missing values in the" + " training data\n"; return ret; } public static void main(String[] arg) { int i; Wrapper w = new Wrapper(); System.out.println(""); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); System.out.println( "// Companion code to ICML'22 paper \"Generative Trees: Adversarial and Copycat\", by" + " Richard Nock and Mathieu Guillame-Bert //"); System.out.println( "// (copycat training of generative trees) " + " //"); if (arg.length == 0) { System.out.println("// *No parameters*. Run 'java Wrapper --help' for more"); System.exit(0); } System.out.println( "// Help &<SUF> + " //"); System.out.println( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"); for (i = 0; i < arg.length; i++) { if (arg[i].equals(HELP)) { System.out.println(help()); System.exit(0); } w.fit_vars(arg[i]); } w.summary(); w.simple_go(); System.out.println("\nBibTex:"); System.out.println("@inproceedings{ngbGT,"); System.out.println(" title={Generative Trees: Adversarial and Copycat},"); System.out.println(" author={R. Nock and M. Guillame-Bert},"); System.out.println(" booktitle={39$^{~th}$ International Conference on Machine Learning},"); System.out.println(" year={2022}"); System.out.println("}\n"); } public void simple_go() { Algorithm.INIT(); long b, e; Vector<Example> v_gen; System.out.print("Loading stuff start... "); b = System.currentTimeMillis(); myDomain = new Domain(this); myAlgos = new Algorithm(myDomain); e = System.currentTimeMillis(); loading_time = e - b; System.out.println("Loading stuff ok (time elapsed: " + loading_time + " ms).\n"); String[] parameters = { "@MatuErr", "1.0", "COPYCAT", number_iterations + "", copycat_local_generation + "" }; Vector<String> params = new Vector<>(Arrays.asList(parameters)); myAlgos.addAlgorithm(params); System.out.print("Learning the generator... "); b = System.currentTimeMillis(); Generator_Tree gt = myAlgos.simple_go(); e = System.currentTimeMillis(); gt_computation_time = e - b; System.out.println( "ok (time elapsed: " + gt_computation_time + " ms).\n\nGenerative tree learned: " + gt); System.out.print("Computing GT marginals histograms... "); b = System.currentTimeMillis(); gt.compute_generator_histograms(); e = System.currentTimeMillis(); marginal_computation_time = e - b; System.out.println("ok (time elapsed: " + marginal_computation_time + " ms)."); System.out.print("Saving the GT... "); b = System.currentTimeMillis(); Generator_Tree.SAVE_GENERATOR_TREE(gt, working_directory + "/" + generator_filename, ""); e = System.currentTimeMillis(); saving_generator_time = e - b; System.out.println("ok (time elapsed: " + saving_generator_time + " ms)."); System.out.print("Generating " + size_generated + " examples using the GT... "); b = System.currentTimeMillis(); v_gen = gt.generate_sample_with_density(size_generated); e = System.currentTimeMillis(); generate_examples_time = e - b; System.out.println("ok (time elapsed: " + generate_examples_time + " ms)."); if ((has_missing_values) && (impute_missing)) { System.out.print("Imputing examples using the GT... "); b = System.currentTimeMillis(); impute_and_save(gt); e = System.currentTimeMillis(); imputation_time = e - b; System.out.println("ok (time elapsed: " + imputation_time + " ms)."); } System.out.print("Saving generated sample... "); b = System.currentTimeMillis(); save_sample(v_gen); e = System.currentTimeMillis(); saving_generated_sample_time = e - b; System.out.println("ok (time elapsed: " + saving_generated_sample_time + " ms)."); if ((x_name != null) && (y_name != null)) { System.out.print("Saving density plot sample... "); b = System.currentTimeMillis(); save_density_plot_sample(v_gen, index_x_name, index_y_name); e = System.currentTimeMillis(); saving_density_plot_generated_sample_time = e - b; System.out.println( "ok (time elapsed: " + saving_density_plot_generated_sample_time + " ms)."); } System.out.print("Saving stats file... "); b = System.currentTimeMillis(); save_stats(gt); e = System.currentTimeMillis(); saving_stats_time = e - b; System.out.println("ok (time elapsed: " + saving_stats_time + " ms)."); System.out.println("All finished. Stopping..."); myDomain.myMemoryMonitor.stop(); } public void save_density_plot_sample(Vector<Example> v_gen, int x, int y) { FileWriter f; int i; String nameFile = working_directory + "/" + densityplot_filename; try { f = new FileWriter(nameFile); f.write("//" + x_name + "," + y_name + ",density_value\n"); for (i = 0; i < v_gen.size(); i++) f.write( ((Example) v_gen.elementAt(i)).toStringSaveDensity(index_x_name, index_y_name) + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void save_sample(Vector<Example> v_gen) { FileWriter f; int i; String nameFile = path_to_generated_samples + "/" + blueprint_save_name; try { f = new FileWriter(nameFile); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write(myDomain.myDS.features_names_from_file[i]); if (i < myDomain.myDS.features_names_from_file.length - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } f.write("\n"); for (i = 0; i < v_gen.size(); i++) f.write(((Example) v_gen.elementAt(i)).toStringSave() + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void impute_and_save(Generator_Tree gt) { FileWriter f; int i, j; String nameFile = working_directory + "/" + spec_name + "_imputed.csv"; Example ee, ee_cop; try { f = new FileWriter(nameFile); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write(myDomain.myDS.features_names_from_file[i]); if (i < myDomain.myDS.features_names_from_file.length - 1) f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]); } f.write("\n"); for (i = 0; i < myDomain.myDS.number_examples_total_from_file; i++) { if (i % (myDomain.myDS.number_examples_total_from_file / 10) == 0) System.out.print((i / (myDomain.myDS.number_examples_total_from_file / 10)) * 10 + "% "); ee = (Example) myDomain.myDS.examples_from_file.elementAt(i); ee_cop = Example.copyOf(ee); if (ee.contains_unknown_values()) { gt.impute_all_values_from_one_leaf(ee_cop); } f.write(ee_cop.toStringSave() + "\n"); } f.close(); } catch (IOException e) { Dataset.perror("Experiments.class :: Saving results error in file " + nameFile); } } public void save_stats(Generator_Tree gt) { int i; FileWriter f = null; int[] node_counts = new int[myDomain.myDS.features_names_from_file.length]; String output_stats_additional = output_stats_file + "_more.txt"; long time_gt_plus_generation = gt_computation_time + generate_examples_time; long time_gt_plus_imputation = -1; if ((has_missing_values) && (impute_missing)) time_gt_plus_imputation = gt_computation_time + imputation_time; try { f = new FileWriter(output_stats_file); f.write("{\n"); f.write( " \"running_time_seconds\": " + DF8.format(((double) gt_computation_time + generate_examples_time) / 1000) + ",\n"); f.write(" \"gt_number_nodes\": " + gt.number_nodes + ",\n"); f.write(" \"gt_depth\": " + gt.depth + ",\n"); f.write( " \"running_time_gt_training_plus_exemple_generation\": " + DF8.format(((double) time_gt_plus_generation / 1000)) + ",\n"); if ((has_missing_values) && (impute_missing)) f.write( " \"running_time_gt_training_plus_imputation\": " + DF8.format(((double) time_gt_plus_imputation / 1000)) + "\n"); f.write("}\n"); f.close(); } catch (IOException e) { Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_file); } try { f = new FileWriter(output_stats_additional); f.write("// flag values used: "); for (i = 0; i < flags_values.length; i++) f.write(" [" + ALL_FLAGS[i] + ":" + flags_values[i] + "] "); f.write("\n\n"); f.write("// Time to learn the generator: " + gt_computation_time + " ms.\n"); f.write("// Time to generate sample: " + generate_examples_time + " ms.\n"); // saves the gt histograms for comparison f.write("\n// GT Histograms of marginals\n"); for (i = 0; i < gt.gt_histograms.size(); i++) { f.write((gt.gt_histograms.elementAt(i)).toStringSave()); f.write("//\n"); } gt.root.recursive_fill_node_counts(node_counts, myDomain.myDS.features_names_from_file); f.write("\n// GT node counts per feature name\n"); for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) { f.write("// " + myDomain.myDS.features_names_from_file[i] + " : " + node_counts[i] + "\n"); } f.close(); } catch (IOException e) { Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_additional); } } public void summary() { int i; System.out.println("\nRunning copycat generator training with the following inputs:"); System.out.println(" * dataset path to train generator:" + path_and_name_of_domain_dataset); System.out.println(" * working directory:" + working_directory); System.out.println( " * generated samples (" + size_generated + " examples) stored in directory " + path_to_generated_samples + " with filename " + blueprint_save_name); System.out.println( " * generator (gt) stored in working directory with filename " + generator_filename); System.out.println(" * stats file at " + output_stats_file); if (spec_path == null) Dataset.warning(" No path information in --dataset_spec"); else if (!path_and_name_of_domain_dataset.equals(spec_path)) Dataset.warning(" Non identical information in --dataset_spec path vs --dataset\n"); if (impute_missing) System.out.println( " * imputed sample saved at filename " + working_directory + "/" + spec_name + "_imputed.csv"); if ((x_name != null) && (y_name != null) && (!x_name.equals("")) && (!y_name.equals(""))) { densityplot_filename = blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.')) + "_2DDensity_plot_X_" + x_name + "_Y_" + y_name + blueprint_save_name.substring( blueprint_save_name.lastIndexOf('.'), blueprint_save_name.length()); System.out.println( " * 2D density plot for (" + x_name + "," + y_name + ") stored in working directory with filename " + densityplot_filename); } System.out.print(" * flags (non null): "); for (i = 0; i < flags_values.length; i++) if (flags_values[i] != null) System.out.print("[" + ALL_FLAGS[i] + ":" + flags_values[i] + "] "); System.out.println(""); if (flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING] != null) Unknown_Feature_Value.S_UNKNOWN = flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING]; if (flags_values[ALL_FLAGS_FORCE_INTEGER_CODING] != null) force_integer_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_INTEGER_CODING]); if (flags_values[ALL_FLAGS_FORCE_BINARY_CODING] != null) force_binary_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_BINARY_CODING]); if (flags_values[ALL_FLAGS_FASTER_INDUCTION] != null) faster_induction = Boolean.parseBoolean(flags_values[ALL_FLAGS_FASTER_INDUCTION]); if (flags_values[ALL_FLAGS_INDEX_ITERATIONS] != null) number_iterations = Integer.parseInt(flags_values[ALL_FLAGS_INDEX_ITERATIONS]); if (flags_values[ALL_FLAGS_COPYCAT_LOCAL_GENERATION] != null) copycat_local_generation = Boolean.parseBoolean(flags_values[ALL_FLAGS_COPYCAT_LOCAL_GENERATION]); Boost.COPYCAT_GENERATE_WITH_WHOLE_GT = !copycat_local_generation; if (flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS] != null) { Histogram.NUMBER_CONTINUOUS_FEATURE_BINS = Integer.parseInt(flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS]); Histogram.MAX_NUMBER_INTEGER_FEATURE_BINS = Integer.parseInt(flags_values[ALL_FLAGS_NUMBER_BINS_FOR_HISTOGRAMS]); } Dataset.NUMBER_GENERATED_EXAMPLES_DEFAULT = -1; Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS = true; Discriminator_Tree.RANDOMISE_SPLIT_FINDING_WHEN_TOO_MANY_SPLITS = faster_induction; System.out.println(""); } public void fit_vars(String s) { String dummys; if (s.contains(DATASET)) { path_and_name_of_domain_dataset = s.substring(DATASET.length(), s.length()); spec_name = path_and_name_of_domain_dataset.substring( path_and_name_of_domain_dataset.lastIndexOf('/') + 1, path_and_name_of_domain_dataset.lastIndexOf('.')); } else if (s.contains(DATASET_SPEC)) { spec_path = spec_label = spec_task = null; int i, begin_ind, end_ind; String[] values = new String[4]; int[] index_tokens = {0, 0, 0, 0}; for (i = 0; i < DATASET_TOKENS.length; i++) { if (s.indexOf(DATASET_TOKENS[i]) != s.lastIndexOf(DATASET_TOKENS[i])) Dataset.perror( "Wrapper.class :: more than one occurrence of " + DATASET_TOKENS[i] + " in string" + s); if (s.indexOf(DATASET_TOKENS[i]) == -1) Dataset.perror( "Wrapper.class :: zero occurrence of " + DATASET_TOKENS[i] + " in string" + s); else index_tokens[i] = s.indexOf(DATASET_TOKENS[i]); } for (i = 0; i < DATASET_TOKENS.length - 1; i++) if (index_tokens[i] > index_tokens[i + 1]) Dataset.perror( "Wrapper.class :: token " + DATASET_TOKENS[i] + " should appear before token " + DATASET_TOKENS[i + 1] + " in string" + s); for (i = 0; i < DATASET_TOKENS.length; i++) { begin_ind = index_tokens[i] + DATASET_TOKENS[i].length(); if (i == DATASET_TOKENS.length - 1) end_ind = s.length(); else end_ind = index_tokens[i + 1] - 1; dummys = s.substring(begin_ind, end_ind); values[i] = dummys.substring(dummys.indexOf('\"') + 1, dummys.lastIndexOf('\"')); } prefix_domain = spec_name; spec_path = values[1]; spec_label = values[2]; spec_task = values[3]; } else if (s.contains(NUM_SAMPLES)) { size_generated = Integer.parseInt(s.substring(NUM_SAMPLES.length(), s.length())); } else if (s.contains(WORK_DIR)) { working_directory = s.substring(WORK_DIR.length(), s.length()); } else if (s.contains(OUTPUT_SAMPLES)) { dummys = s.substring(OUTPUT_SAMPLES.length(), s.length()); path_to_generated_samples = dummys.substring(0, dummys.lastIndexOf('/')); blueprint_save_name = dummys.substring(dummys.lastIndexOf('/') + 1, dummys.length()); generator_filename = PREFIX_GENERATOR + blueprint_save_name; } else if (s.contains(OUTPUT_STATS)) { output_stats_file = s.substring(OUTPUT_STATS.length(), s.length()); output_stats_directory = s.substring(OUTPUT_STATS.length(), s.lastIndexOf('/')); } else if (s.contains(X)) { x_name = s.substring(X.length(), s.length()); } else if (s.contains(Y)) { y_name = s.substring(Y.length(), s.length()); } else if (s.contains(FLAGS)) { dummys = ((s.substring(FLAGS.length(), s.length())).replaceAll(" ", "")).replaceAll("=", ""); if (!dummys.substring(0, 1).equals("{")) Dataset.perror("Wrapper.class :: FLAGS flags does not begin with '{'"); if (!dummys.substring(dummys.length() - 1, dummys.length()).equals("}")) Dataset.perror("Wrapper.class :: FLAGS flags does not end with '}'"); dummys = (dummys.substring(1, dummys.length() - 1)).replace("\"", ""); int b = 0, e = -1, i; String subs, tags, vals; while (e < dummys.length()) { b = e + 1; do { e++; } while ((e < dummys.length()) && (!dummys.substring(e, e + 1).equals(","))); subs = dummys.substring(b, e); if (!subs.contains(":")) Dataset.perror("Wrapper.class :: flags string " + subs + " not of the syntax tag:value"); tags = subs.substring(0, subs.lastIndexOf(':')); vals = subs.substring(subs.lastIndexOf(':') + 1, subs.length()); i = 0; do { if (!ALL_FLAGS[i].equals(tags)) i++; } while ((i < ALL_FLAGS.length) && (!ALL_FLAGS[i].equals(tags))); if (i == ALL_FLAGS.length) Dataset.perror("Wrapper.class :: flags string " + tags + " not in authorized tags"); flags_values[i] = vals; } } else if (s.contains(IMPUTE_MISSING)) { impute_missing = Boolean.parseBoolean(s.substring(IMPUTE_MISSING.length(), s.length())); } if ((x_name != null) && (y_name != null) && (x_name.equals(y_name))) Dataset.perror( "Wrapper.class :: density plot requested on the same X and Y variable = " + x_name); } }
456_13
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.sort; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.Scorable; import org.elasticsearch.common.lucene.ScorerAware; import org.elasticsearch.common.util.BigArray; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.BitArray; import org.elasticsearch.common.util.DoubleArray; import org.elasticsearch.common.util.FloatArray; import org.elasticsearch.common.util.LongArray; import org.elasticsearch.core.Releasable; import org.elasticsearch.core.Releasables; import org.elasticsearch.search.DocValueFormat; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import static java.util.Collections.emptyList; /** * Type specialized sort implementations designed for use in aggregations. * Aggregations have a couple of super interesting characteristics: * <ul> * <li>They can have many, many buckets so this implementation backs to * {@link BigArrays} so it doesn't need to allocate any objects per bucket * and the circuit breaker in {@linkplain BigArrays} will automatically * track memory usage and abort execution if it grows too large.</li> * <li>Its fairly common for a bucket to be collected but not returned so * these implementations delay as much work as possible until collection</li> * </ul> * <p> * Every bucket is in one of two states: "gathering" or min/max "heap". While * "gathering" the next empty slot is stored in the "root" offset of the * bucket and collecting a value is just adding it in the next slot bumping * the tracking value at the root. So collecting values is {@code O(1)}. * Extracting the results in sorted order is {@code O(n * log n)} because, * well, sorting is {@code O(n * log n)}. When a bucket has collected * {@link #bucketSize} entries it is converted into a min "heap" in * {@code O(n)} time. Or into max heap, if {@link #order} is ascending. * </p> * <p> * Once a "heap", collecting a document is the heap-standard {@code O(log n)} * worst case. Critically, it is a very fast {@code O(1)} to check if a value * is competitive at all which, so long as buckets aren't hit in reverse * order, they mostly won't be. Extracting results in sorted order is still * {@code O(n * log n)}. * </p> * <p> * When we first collect a bucket we make sure that we've allocated enough * slots to hold all sort values for the entire bucket. In other words: the * storage is "dense" and we don't try to save space when storing partially * filled buckets. * </p> * <p> * We actually *oversize* the allocations * (like {@link BigArrays#overSize(long)}) to get amortized linear number * of allocations and to play well with our paged arrays. * </p> */ public abstract class BucketedSort implements Releasable { /** * Callbacks for storing extra data along with competitive sorts. */ public interface ExtraData { /** * Swap the position of two bits of extra data. * <p> * Both parameters will have previously been loaded by * {@link Loader#loadFromDoc(long, int)} so the implementer shouldn't * need to grow the underlying storage to implement this. * </p> */ void swap(long lhs, long rhs); /** * Prepare to load extra data from a leaf. */ Loader loader(LeafReaderContext ctx) throws IOException; @FunctionalInterface interface Loader { /** * Load extra data from a doc. * <p> * Implementers <strong>should</strong> grow their underlying * storage to fit the {@code index}. * </p> */ void loadFromDoc(long index, int doc) throws IOException; } } /** * An implementation of {@linkplain ExtraData} that does nothing. */ public static final ExtraData NOOP_EXTRA_DATA = new ExtraData() { @Override public void swap(long lhs, long rhs) {} @Override public Loader loader(LeafReaderContext ctx) { return (index, doc) -> {}; } }; protected final BigArrays bigArrays; private final SortOrder order; private final DocValueFormat format; private final int bucketSize; protected final ExtraData extra; /** * {@code true} if the bucket is in heap mode, {@code false} if * it is still gathering. */ private final BitArray heapMode; protected BucketedSort(BigArrays bigArrays, SortOrder order, DocValueFormat format, int bucketSize, ExtraData extra) { this.bigArrays = bigArrays; this.order = order; this.format = format; this.bucketSize = bucketSize; this.extra = extra; heapMode = new BitArray(1, bigArrays); } /** * The order of the sort. */ public final SortOrder getOrder() { return order; } /** * The format to use when presenting the values. */ public final DocValueFormat getFormat() { return format; } /** * The number of values to store per bucket. */ public int getBucketSize() { return bucketSize; } /** * Used with {@link BucketedSort#getValues(long, ResultBuilder)} to * build results from the sorting operation. */ @FunctionalInterface public interface ResultBuilder<T> { T build(long index, SortValue sortValue) throws IOException; } /** * Get the values for a bucket if it has been collected. If it hasn't * then returns an empty list. * @param builder builds results. See {@link ExtraData} for how to store * data along side the sort for this to extract. */ public final <T extends Comparable<T>> List<T> getValues(long bucket, ResultBuilder<T> builder) throws IOException { long rootIndex = bucket * bucketSize; if (rootIndex >= values().size()) { // We've never seen this bucket. return emptyList(); } long start = inHeapMode(bucket) ? rootIndex : (rootIndex + getNextGatherOffset(rootIndex) + 1); long end = rootIndex + bucketSize; List<T> result = new ArrayList<>(bucketSize); for (long index = start; index < end; index++) { result.add(builder.build(index, getValue(index))); } // TODO we usually have a heap here so we could use that to build the results sorted. result.sort(order.wrap(Comparator.<T>naturalOrder())); return result; } /** * Get the values for a bucket if it has been collected. If it hasn't * then returns an empty array. */ public final List<SortValue> getValues(long bucket) throws IOException { return getValues(bucket, (i, sv) -> sv); } /** * Is this bucket a min heap {@code true} or in gathering mode {@code false}? */ public boolean inHeapMode(long bucket) { return heapMode.get(bucket); } /** * Get the {@linkplain Leaf} implementation that'll do that actual collecting. * @throws IOException most implementations need to perform IO to prepare for each leaf */ public abstract Leaf forLeaf(LeafReaderContext ctx) throws IOException; /** * Does this sort need scores? Most don't, but sorting on {@code _score} does. */ public abstract boolean needsScores(); /** * The {@linkplain BigArray} backing this sort. */ protected abstract BigArray values(); /** * Grow the {@linkplain BigArray} backing this sort to account for new buckets. * This will only be called if the array is too small. */ protected abstract void growValues(long minSize); /** * Get the next index that should be "gathered" for a bucket rooted * at {@code rootIndex}. */ protected abstract int getNextGatherOffset(long rootIndex); /** * Set the next index that should be "gathered" for a bucket rooted * at {@code rootIndex}. */ protected abstract void setNextGatherOffset(long rootIndex, int offset); /** * Get the value at an index. */ protected abstract SortValue getValue(long index); /** * {@code true} if the entry at index {@code lhs} is "better" than * the entry at {@code rhs}. "Better" in this means "lower" for * {@link SortOrder#ASC} and "higher" for {@link SortOrder#DESC}. */ protected abstract boolean betterThan(long lhs, long rhs); /** * Swap the data at two indices. */ protected abstract void swap(long lhs, long rhs); /** * Initialize the gather offsets after setting up values. Subclasses * should call this once, after setting up their {@link #values()}. */ protected final void initGatherOffsets() { setNextGatherOffsets(0); } /** * Allocate storage for more buckets and store the "next gather offset" * for those new buckets. */ private void grow(long minSize) { long oldMax = values().size() - 1; growValues(minSize); // Set the next gather offsets for all newly allocated buckets. setNextGatherOffsets(oldMax - (oldMax % getBucketSize()) + getBucketSize()); } /** * Maintain the "next gather offsets" for newly allocated buckets. */ private void setNextGatherOffsets(long startingAt) { int nextOffset = getBucketSize() - 1; for (long bucketRoot = startingAt; bucketRoot < values().size(); bucketRoot += getBucketSize()) { setNextGatherOffset(bucketRoot, nextOffset); } } /** * Heapify a bucket who's entries are in random order. * <p> * This works by validating the heap property on each node, iterating * "upwards", pushing any out of order parents "down". Check out the * <a href="https://en.wikipedia.org/w/index.php?title=Binary_heap&oldid=940542991#Building_a_heap">wikipedia</a> * entry on binary heaps for more about this. * </p> * <p> * While this *looks* like it could easily be {@code O(n * log n)}, it is * a fairly well studied algorithm attributed to Floyd. There's * been a bunch of work that puts this at {@code O(n)}, close to 1.88n worst * case. * </p> * <ul> * <li>Hayward, Ryan; McDiarmid, Colin (1991). * <a href="https://web.archive.org/web/20160205023201/http://www.stats.ox.ac.uk/__data/assets/pdf_file/0015/4173/heapbuildjalg.pdf"> * Average Case Analysis of Heap Building byRepeated Insertion</a> J. Algorithms. * <li>D.E. Knuth, ”The Art of Computer Programming, Vol. 3, Sorting and Searching”</li> * </ul> * @param rootIndex the index the start of the bucket */ private void heapify(long rootIndex) { int maxParent = bucketSize / 2 - 1; for (int parent = maxParent; parent >= 0; parent--) { downHeap(rootIndex, parent); } } /** * Correct the heap invariant of a parent and its children. This * runs in {@code O(log n)} time. * @param rootIndex index of the start of the bucket * @param parent Index within the bucket of the parent to check. * For example, 0 is the "root". */ private void downHeap(long rootIndex, int parent) { while (true) { long parentIndex = rootIndex + parent; int worst = parent; long worstIndex = parentIndex; int leftChild = parent * 2 + 1; long leftIndex = rootIndex + leftChild; if (leftChild < bucketSize) { if (betterThan(worstIndex, leftIndex)) { worst = leftChild; worstIndex = leftIndex; } int rightChild = leftChild + 1; long rightIndex = rootIndex + rightChild; if (rightChild < bucketSize && betterThan(worstIndex, rightIndex)) { worst = rightChild; worstIndex = rightIndex; } } if (worst == parent) { break; } swap(worstIndex, parentIndex); extra.swap(worstIndex, parentIndex); parent = worst; } } @Override public final void close() { Releasables.close(values(), heapMode); } /** * Performs the actual collection against a {@linkplain LeafReaderContext}. */ public abstract class Leaf implements ScorerAware { private final LeafReaderContext ctx; private ExtraData.Loader loader = null; protected Leaf(LeafReaderContext ctx) { this.ctx = ctx; } /** * Collect this doc, returning {@code true} if it is competitive. */ public final void collect(int doc, long bucket) throws IOException { if (false == advanceExact(doc)) { return; } long rootIndex = bucket * bucketSize; if (inHeapMode(bucket)) { if (docBetterThan(rootIndex)) { // TODO a "bottom up" insert would save a couple of comparisons. Worth it? setIndexToDocValue(rootIndex); loader().loadFromDoc(rootIndex, doc); downHeap(rootIndex, 0); } return; } // Gathering mode long requiredSize = rootIndex + bucketSize; if (values().size() < requiredSize) { grow(requiredSize); } int next = getNextGatherOffset(rootIndex); assert 0 <= next && next < bucketSize : "Expected next to be in the range of valid buckets [0 <= " + next + " < " + bucketSize + "]"; long index = next + rootIndex; setIndexToDocValue(index); loader().loadFromDoc(index, doc); if (next == 0) { heapMode.set(bucket); heapify(rootIndex); } else { setNextGatherOffset(rootIndex, next - 1); } } /** * Read the sort value from {@code doc} and return {@code true} * if there is a value for that document. Otherwise return * {@code false} and the sort will skip that document. */ protected abstract boolean advanceExact(int doc) throws IOException; /** * Set the value at the index to the value of the document to which * we just advanced. */ protected abstract void setIndexToDocValue(long index); /** * {@code true} if the sort value for the doc is "better" than the * entry at {@code index}. "Better" in means is "lower" for * {@link SortOrder#ASC} and "higher" for {@link SortOrder#DESC}. */ protected abstract boolean docBetterThan(long index); /** * Get the extra data loader, building it if we haven't yet built one for this leaf. */ private ExtraData.Loader loader() throws IOException { if (loader == null) { loader = extra.loader(ctx); } return loader; } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code double} keys. */ public abstract static class ForDoubles extends BucketedSort { private DoubleArray values; @SuppressWarnings("this-escape") public ForDoubles(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); boolean success = false; try { values = bigArrays.newDoubleArray(getBucketSize(), false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override public boolean needsScores() { return false; } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { // This cast is safe because all ints fit accurately into a double. return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Double.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { double tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract double docValue(); @Override public final void setScorer(Scorable scorer) {} @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Double.compare(docValue(), values.get(index)) < 0; } } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code float} keys. */ public abstract static class ForFloats extends BucketedSort { /** * The maximum size of buckets this can store. This is because we * store the next offset to write to in a float and floats only have * {@code 23} bits of mantissa so they can't accurate store values * higher than {@code 2 ^ 24}. */ public static final int MAX_BUCKET_SIZE = (int) Math.pow(2, 24); private FloatArray values; @SuppressWarnings("this-escape") public ForFloats(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); if (bucketSize > MAX_BUCKET_SIZE) { close(); throw new IllegalArgumentException("bucket size must be less than [2^24] but was [" + bucketSize + "]"); } boolean success = false; try { values = bigArrays.newFloatArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { /* * This cast will not lose precision because we make sure never * to write values here that float can't store precisely. */ return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Float.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { float tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract float docValue(); @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Float.compare(docValue(), values.get(index)) < 0; } } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code long} keys. */ public abstract static class ForLongs extends BucketedSort { private LongArray values; @SuppressWarnings("this-escape") public ForLongs(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); boolean success = false; try { values = bigArrays.newLongArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override public final boolean needsScores() { return false; } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Long.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { long tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract long docValue(); @Override public final void setScorer(Scorable scorer) {} @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Long.compare(docValue(), values.get(index)) < 0; } } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/search/sort/BucketedSort.java
6,279
// We've never seen this bucket.
line_comment
nl
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.sort; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.Scorable; import org.elasticsearch.common.lucene.ScorerAware; import org.elasticsearch.common.util.BigArray; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.BitArray; import org.elasticsearch.common.util.DoubleArray; import org.elasticsearch.common.util.FloatArray; import org.elasticsearch.common.util.LongArray; import org.elasticsearch.core.Releasable; import org.elasticsearch.core.Releasables; import org.elasticsearch.search.DocValueFormat; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import static java.util.Collections.emptyList; /** * Type specialized sort implementations designed for use in aggregations. * Aggregations have a couple of super interesting characteristics: * <ul> * <li>They can have many, many buckets so this implementation backs to * {@link BigArrays} so it doesn't need to allocate any objects per bucket * and the circuit breaker in {@linkplain BigArrays} will automatically * track memory usage and abort execution if it grows too large.</li> * <li>Its fairly common for a bucket to be collected but not returned so * these implementations delay as much work as possible until collection</li> * </ul> * <p> * Every bucket is in one of two states: "gathering" or min/max "heap". While * "gathering" the next empty slot is stored in the "root" offset of the * bucket and collecting a value is just adding it in the next slot bumping * the tracking value at the root. So collecting values is {@code O(1)}. * Extracting the results in sorted order is {@code O(n * log n)} because, * well, sorting is {@code O(n * log n)}. When a bucket has collected * {@link #bucketSize} entries it is converted into a min "heap" in * {@code O(n)} time. Or into max heap, if {@link #order} is ascending. * </p> * <p> * Once a "heap", collecting a document is the heap-standard {@code O(log n)} * worst case. Critically, it is a very fast {@code O(1)} to check if a value * is competitive at all which, so long as buckets aren't hit in reverse * order, they mostly won't be. Extracting results in sorted order is still * {@code O(n * log n)}. * </p> * <p> * When we first collect a bucket we make sure that we've allocated enough * slots to hold all sort values for the entire bucket. In other words: the * storage is "dense" and we don't try to save space when storing partially * filled buckets. * </p> * <p> * We actually *oversize* the allocations * (like {@link BigArrays#overSize(long)}) to get amortized linear number * of allocations and to play well with our paged arrays. * </p> */ public abstract class BucketedSort implements Releasable { /** * Callbacks for storing extra data along with competitive sorts. */ public interface ExtraData { /** * Swap the position of two bits of extra data. * <p> * Both parameters will have previously been loaded by * {@link Loader#loadFromDoc(long, int)} so the implementer shouldn't * need to grow the underlying storage to implement this. * </p> */ void swap(long lhs, long rhs); /** * Prepare to load extra data from a leaf. */ Loader loader(LeafReaderContext ctx) throws IOException; @FunctionalInterface interface Loader { /** * Load extra data from a doc. * <p> * Implementers <strong>should</strong> grow their underlying * storage to fit the {@code index}. * </p> */ void loadFromDoc(long index, int doc) throws IOException; } } /** * An implementation of {@linkplain ExtraData} that does nothing. */ public static final ExtraData NOOP_EXTRA_DATA = new ExtraData() { @Override public void swap(long lhs, long rhs) {} @Override public Loader loader(LeafReaderContext ctx) { return (index, doc) -> {}; } }; protected final BigArrays bigArrays; private final SortOrder order; private final DocValueFormat format; private final int bucketSize; protected final ExtraData extra; /** * {@code true} if the bucket is in heap mode, {@code false} if * it is still gathering. */ private final BitArray heapMode; protected BucketedSort(BigArrays bigArrays, SortOrder order, DocValueFormat format, int bucketSize, ExtraData extra) { this.bigArrays = bigArrays; this.order = order; this.format = format; this.bucketSize = bucketSize; this.extra = extra; heapMode = new BitArray(1, bigArrays); } /** * The order of the sort. */ public final SortOrder getOrder() { return order; } /** * The format to use when presenting the values. */ public final DocValueFormat getFormat() { return format; } /** * The number of values to store per bucket. */ public int getBucketSize() { return bucketSize; } /** * Used with {@link BucketedSort#getValues(long, ResultBuilder)} to * build results from the sorting operation. */ @FunctionalInterface public interface ResultBuilder<T> { T build(long index, SortValue sortValue) throws IOException; } /** * Get the values for a bucket if it has been collected. If it hasn't * then returns an empty list. * @param builder builds results. See {@link ExtraData} for how to store * data along side the sort for this to extract. */ public final <T extends Comparable<T>> List<T> getValues(long bucket, ResultBuilder<T> builder) throws IOException { long rootIndex = bucket * bucketSize; if (rootIndex >= values().size()) { // We've never<SUF> return emptyList(); } long start = inHeapMode(bucket) ? rootIndex : (rootIndex + getNextGatherOffset(rootIndex) + 1); long end = rootIndex + bucketSize; List<T> result = new ArrayList<>(bucketSize); for (long index = start; index < end; index++) { result.add(builder.build(index, getValue(index))); } // TODO we usually have a heap here so we could use that to build the results sorted. result.sort(order.wrap(Comparator.<T>naturalOrder())); return result; } /** * Get the values for a bucket if it has been collected. If it hasn't * then returns an empty array. */ public final List<SortValue> getValues(long bucket) throws IOException { return getValues(bucket, (i, sv) -> sv); } /** * Is this bucket a min heap {@code true} or in gathering mode {@code false}? */ public boolean inHeapMode(long bucket) { return heapMode.get(bucket); } /** * Get the {@linkplain Leaf} implementation that'll do that actual collecting. * @throws IOException most implementations need to perform IO to prepare for each leaf */ public abstract Leaf forLeaf(LeafReaderContext ctx) throws IOException; /** * Does this sort need scores? Most don't, but sorting on {@code _score} does. */ public abstract boolean needsScores(); /** * The {@linkplain BigArray} backing this sort. */ protected abstract BigArray values(); /** * Grow the {@linkplain BigArray} backing this sort to account for new buckets. * This will only be called if the array is too small. */ protected abstract void growValues(long minSize); /** * Get the next index that should be "gathered" for a bucket rooted * at {@code rootIndex}. */ protected abstract int getNextGatherOffset(long rootIndex); /** * Set the next index that should be "gathered" for a bucket rooted * at {@code rootIndex}. */ protected abstract void setNextGatherOffset(long rootIndex, int offset); /** * Get the value at an index. */ protected abstract SortValue getValue(long index); /** * {@code true} if the entry at index {@code lhs} is "better" than * the entry at {@code rhs}. "Better" in this means "lower" for * {@link SortOrder#ASC} and "higher" for {@link SortOrder#DESC}. */ protected abstract boolean betterThan(long lhs, long rhs); /** * Swap the data at two indices. */ protected abstract void swap(long lhs, long rhs); /** * Initialize the gather offsets after setting up values. Subclasses * should call this once, after setting up their {@link #values()}. */ protected final void initGatherOffsets() { setNextGatherOffsets(0); } /** * Allocate storage for more buckets and store the "next gather offset" * for those new buckets. */ private void grow(long minSize) { long oldMax = values().size() - 1; growValues(minSize); // Set the next gather offsets for all newly allocated buckets. setNextGatherOffsets(oldMax - (oldMax % getBucketSize()) + getBucketSize()); } /** * Maintain the "next gather offsets" for newly allocated buckets. */ private void setNextGatherOffsets(long startingAt) { int nextOffset = getBucketSize() - 1; for (long bucketRoot = startingAt; bucketRoot < values().size(); bucketRoot += getBucketSize()) { setNextGatherOffset(bucketRoot, nextOffset); } } /** * Heapify a bucket who's entries are in random order. * <p> * This works by validating the heap property on each node, iterating * "upwards", pushing any out of order parents "down". Check out the * <a href="https://en.wikipedia.org/w/index.php?title=Binary_heap&oldid=940542991#Building_a_heap">wikipedia</a> * entry on binary heaps for more about this. * </p> * <p> * While this *looks* like it could easily be {@code O(n * log n)}, it is * a fairly well studied algorithm attributed to Floyd. There's * been a bunch of work that puts this at {@code O(n)}, close to 1.88n worst * case. * </p> * <ul> * <li>Hayward, Ryan; McDiarmid, Colin (1991). * <a href="https://web.archive.org/web/20160205023201/http://www.stats.ox.ac.uk/__data/assets/pdf_file/0015/4173/heapbuildjalg.pdf"> * Average Case Analysis of Heap Building byRepeated Insertion</a> J. Algorithms. * <li>D.E. Knuth, ”The Art of Computer Programming, Vol. 3, Sorting and Searching”</li> * </ul> * @param rootIndex the index the start of the bucket */ private void heapify(long rootIndex) { int maxParent = bucketSize / 2 - 1; for (int parent = maxParent; parent >= 0; parent--) { downHeap(rootIndex, parent); } } /** * Correct the heap invariant of a parent and its children. This * runs in {@code O(log n)} time. * @param rootIndex index of the start of the bucket * @param parent Index within the bucket of the parent to check. * For example, 0 is the "root". */ private void downHeap(long rootIndex, int parent) { while (true) { long parentIndex = rootIndex + parent; int worst = parent; long worstIndex = parentIndex; int leftChild = parent * 2 + 1; long leftIndex = rootIndex + leftChild; if (leftChild < bucketSize) { if (betterThan(worstIndex, leftIndex)) { worst = leftChild; worstIndex = leftIndex; } int rightChild = leftChild + 1; long rightIndex = rootIndex + rightChild; if (rightChild < bucketSize && betterThan(worstIndex, rightIndex)) { worst = rightChild; worstIndex = rightIndex; } } if (worst == parent) { break; } swap(worstIndex, parentIndex); extra.swap(worstIndex, parentIndex); parent = worst; } } @Override public final void close() { Releasables.close(values(), heapMode); } /** * Performs the actual collection against a {@linkplain LeafReaderContext}. */ public abstract class Leaf implements ScorerAware { private final LeafReaderContext ctx; private ExtraData.Loader loader = null; protected Leaf(LeafReaderContext ctx) { this.ctx = ctx; } /** * Collect this doc, returning {@code true} if it is competitive. */ public final void collect(int doc, long bucket) throws IOException { if (false == advanceExact(doc)) { return; } long rootIndex = bucket * bucketSize; if (inHeapMode(bucket)) { if (docBetterThan(rootIndex)) { // TODO a "bottom up" insert would save a couple of comparisons. Worth it? setIndexToDocValue(rootIndex); loader().loadFromDoc(rootIndex, doc); downHeap(rootIndex, 0); } return; } // Gathering mode long requiredSize = rootIndex + bucketSize; if (values().size() < requiredSize) { grow(requiredSize); } int next = getNextGatherOffset(rootIndex); assert 0 <= next && next < bucketSize : "Expected next to be in the range of valid buckets [0 <= " + next + " < " + bucketSize + "]"; long index = next + rootIndex; setIndexToDocValue(index); loader().loadFromDoc(index, doc); if (next == 0) { heapMode.set(bucket); heapify(rootIndex); } else { setNextGatherOffset(rootIndex, next - 1); } } /** * Read the sort value from {@code doc} and return {@code true} * if there is a value for that document. Otherwise return * {@code false} and the sort will skip that document. */ protected abstract boolean advanceExact(int doc) throws IOException; /** * Set the value at the index to the value of the document to which * we just advanced. */ protected abstract void setIndexToDocValue(long index); /** * {@code true} if the sort value for the doc is "better" than the * entry at {@code index}. "Better" in means is "lower" for * {@link SortOrder#ASC} and "higher" for {@link SortOrder#DESC}. */ protected abstract boolean docBetterThan(long index); /** * Get the extra data loader, building it if we haven't yet built one for this leaf. */ private ExtraData.Loader loader() throws IOException { if (loader == null) { loader = extra.loader(ctx); } return loader; } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code double} keys. */ public abstract static class ForDoubles extends BucketedSort { private DoubleArray values; @SuppressWarnings("this-escape") public ForDoubles(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); boolean success = false; try { values = bigArrays.newDoubleArray(getBucketSize(), false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override public boolean needsScores() { return false; } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { // This cast is safe because all ints fit accurately into a double. return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Double.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { double tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract double docValue(); @Override public final void setScorer(Scorable scorer) {} @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Double.compare(docValue(), values.get(index)) < 0; } } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code float} keys. */ public abstract static class ForFloats extends BucketedSort { /** * The maximum size of buckets this can store. This is because we * store the next offset to write to in a float and floats only have * {@code 23} bits of mantissa so they can't accurate store values * higher than {@code 2 ^ 24}. */ public static final int MAX_BUCKET_SIZE = (int) Math.pow(2, 24); private FloatArray values; @SuppressWarnings("this-escape") public ForFloats(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); if (bucketSize > MAX_BUCKET_SIZE) { close(); throw new IllegalArgumentException("bucket size must be less than [2^24] but was [" + bucketSize + "]"); } boolean success = false; try { values = bigArrays.newFloatArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { /* * This cast will not lose precision because we make sure never * to write values here that float can't store precisely. */ return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Float.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { float tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract float docValue(); @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Float.compare(docValue(), values.get(index)) < 0; } } } /** * Superclass for implementations of {@linkplain BucketedSort} for {@code long} keys. */ public abstract static class ForLongs extends BucketedSort { private LongArray values; @SuppressWarnings("this-escape") public ForLongs(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); boolean success = false; try { values = bigArrays.newLongArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override public final boolean needsScores() { return false; } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { return (int) values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Long.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { long tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract class Leaf extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract long docValue(); @Override public final void setScorer(Scorable scorer) {} @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Long.compare(docValue(), values.get(index)) < 0; } } } }
584_1
package com.thealgorithms.sorts; public final class DNFSort { private DNFSort() { } // Sort the input array, the array is assumed to // have values in {0, 1, 2} static void sort012(int[] a, int arr_size) { int low = 0; int high = arr_size - 1; int mid = 0, temp; while (mid <= high) { switch (a[mid]) { case 0: { temp = a[low]; a[low] = a[mid]; a[mid] = temp; low++; mid++; break; } case 1: mid++; break; case 2: { temp = a[mid]; a[mid] = a[high]; a[high] = temp; high--; break; } } } } /* Utility function to print array arr[] */ static void printArray(int[] arr, int arr_size) { for (int i = 0; i < arr_size; i++) { System.out.print(arr[i] + " "); } System.out.println(); } /*Driver function to check for above functions*/ public static void main(String[] args) { int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); printArray(arr, arr_size); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/DNFSort.java
439
// have values in {0, 1, 2}
line_comment
nl
package com.thealgorithms.sorts; public final class DNFSort { private DNFSort() { } // Sort the input array, the array is assumed to // have values<SUF> static void sort012(int[] a, int arr_size) { int low = 0; int high = arr_size - 1; int mid = 0, temp; while (mid <= high) { switch (a[mid]) { case 0: { temp = a[low]; a[low] = a[mid]; a[mid] = temp; low++; mid++; break; } case 1: mid++; break; case 2: { temp = a[mid]; a[mid] = a[high]; a[high] = temp; high--; break; } } } } /* Utility function to print array arr[] */ static void printArray(int[] arr, int arr_size) { for (int i = 0; i < arr_size; i++) { System.out.print(arr[i] + " "); } System.out.println(); } /*Driver function to check for above functions*/ public static void main(String[] args) { int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); printArray(arr, arr_size); } }
603_1
package com.genymobile.scrcpy; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.os.Looper; import android.os.SystemClock; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class SurfaceEncoder implements AsyncProcessor { private static final int DEFAULT_I_FRAME_INTERVAL = 10; // seconds private static final int REPEAT_FRAME_DELAY_US = 100_000; // repeat after 100ms private static final String KEY_MAX_FPS_TO_ENCODER = "max-fps-to-encoder"; // Keep the values in descending order private static final int[] MAX_SIZE_FALLBACK = {2560, 1920, 1600, 1280, 1024, 800}; private static final int MAX_CONSECUTIVE_ERRORS = 3; private final SurfaceCapture capture; private final Streamer streamer; private final String encoderName; private final List<CodecOption> codecOptions; private final int videoBitRate; private final int maxFps; private final boolean downsizeOnError; private boolean firstFrameSent; private int consecutiveErrors; private Thread thread; private final AtomicBoolean stopped = new AtomicBoolean(); public SurfaceEncoder(SurfaceCapture capture, Streamer streamer, int videoBitRate, int maxFps, List<CodecOption> codecOptions, String encoderName, boolean downsizeOnError) { this.capture = capture; this.streamer = streamer; this.videoBitRate = videoBitRate; this.maxFps = maxFps; this.codecOptions = codecOptions; this.encoderName = encoderName; this.downsizeOnError = downsizeOnError; } private void streamScreen() throws IOException, ConfigurationException { Codec codec = streamer.getCodec(); MediaCodec mediaCodec = createMediaCodec(codec, encoderName); MediaFormat format = createFormat(codec.getMimeType(), videoBitRate, maxFps, codecOptions); capture.init(); try { streamer.writeVideoHeader(capture.getSize()); boolean alive; do { Size size = capture.getSize(); format.setInteger(MediaFormat.KEY_WIDTH, size.getWidth()); format.setInteger(MediaFormat.KEY_HEIGHT, size.getHeight()); Surface surface = null; try { mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = mediaCodec.createInputSurface(); capture.start(surface); mediaCodec.start(); alive = encode(mediaCodec, streamer); // do not call stop() on exception, it would trigger an IllegalStateException mediaCodec.stop(); } catch (IllegalStateException | IllegalArgumentException e) { Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage()); if (!prepareRetry(size)) { throw e; } Ln.i("Retrying..."); alive = true; } finally { mediaCodec.reset(); if (surface != null) { surface.release(); } } } while (alive); } finally { mediaCodec.release(); capture.release(); } } private boolean prepareRetry(Size currentSize) { if (firstFrameSent) { ++consecutiveErrors; if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) { // Definitively fail return false; } // Wait a bit to increase the probability that retrying will fix the problem SystemClock.sleep(50); return true; } if (!downsizeOnError) { // Must fail immediately return false; } // Downsizing on error is only enabled if an encoding failure occurs before the first frame (downsizing later could be surprising) int newMaxSize = chooseMaxSizeFallback(currentSize); if (newMaxSize == 0) { // Must definitively fail return false; } boolean accepted = capture.setMaxSize(newMaxSize); if (!accepted) { return false; } // Retry with a smaller size Ln.i("Retrying with -m" + newMaxSize + "..."); return true; } private static int chooseMaxSizeFallback(Size failedSize) { int currentMaxSize = Math.max(failedSize.getWidth(), failedSize.getHeight()); for (int value : MAX_SIZE_FALLBACK) { if (value < currentMaxSize) { // We found a smaller value to reduce the video size return value; } } // No fallback, fail definitively return 0; } private boolean encode(MediaCodec codec, Streamer streamer) throws IOException { boolean eof = false; boolean alive = true; MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); while (!capture.consumeReset() && !eof) { if (stopped.get()) { alive = false; break; } int outputBufferId = codec.dequeueOutputBuffer(bufferInfo, -1); try { if (capture.consumeReset()) { // must restart encoding with new size break; } eof = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0; if (outputBufferId >= 0) { ByteBuffer codecBuffer = codec.getOutputBuffer(outputBufferId); boolean isConfig = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0; if (!isConfig) { // If this is not a config packet, then it contains a frame firstFrameSent = true; consecutiveErrors = 0; } streamer.writePacket(codecBuffer, bufferInfo); } } finally { if (outputBufferId >= 0) { codec.releaseOutputBuffer(outputBufferId, false); } } } if (capture.isClosed()) { // The capture might have been closed internally (for example if the camera is disconnected) alive = false; } return !eof && alive; } private static MediaCodec createMediaCodec(Codec codec, String encoderName) throws IOException, ConfigurationException { if (encoderName != null) { Ln.d("Creating encoder by name: '" + encoderName + "'"); try { return MediaCodec.createByCodecName(encoderName); } catch (IllegalArgumentException e) { Ln.e("Video encoder '" + encoderName + "' for " + codec.getName() + " not found\n" + LogUtils.buildVideoEncoderListMessage()); throw new ConfigurationException("Unknown encoder: " + encoderName); } catch (IOException e) { Ln.e("Could not create video encoder '" + encoderName + "' for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } try { MediaCodec mediaCodec = MediaCodec.createEncoderByType(codec.getMimeType()); Ln.d("Using video encoder: '" + mediaCodec.getName() + "'"); return mediaCodec; } catch (IOException | IllegalArgumentException e) { Ln.e("Could not create default video encoder for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } private static MediaFormat createFormat(String videoMimeType, int bitRate, int maxFps, List<CodecOption> codecOptions) { MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, videoMimeType); format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); // must be present to configure the encoder, but does not impact the actual frame rate, which is variable format.setInteger(MediaFormat.KEY_FRAME_RATE, 60); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, DEFAULT_I_FRAME_INTERVAL); // display the very first frame, and recover from bad quality when no new frames format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_FRAME_DELAY_US); // µs if (maxFps > 0) { // The key existed privately before Android 10: // <https://android.googlesource.com/platform/frameworks/base/+/625f0aad9f7a259b6881006ad8710adce57d1384%5E%21/> // <https://github.com/Genymobile/scrcpy/issues/488#issuecomment-567321437> format.setFloat(KEY_MAX_FPS_TO_ENCODER, maxFps); } if (codecOptions != null) { for (CodecOption option : codecOptions) { String key = option.getKey(); Object value = option.getValue(); CodecUtils.setCodecOption(format, key, value); Ln.d("Video codec option set: " + key + " (" + value.getClass().getSimpleName() + ") = " + value); } } return format; } @Override public void start(TerminationListener listener) { thread = new Thread(() -> { // Some devices (Meizu) deadlock if the video encoding thread has no Looper // <https://github.com/Genymobile/scrcpy/issues/4143> Looper.prepare(); try { streamScreen(); } catch (ConfigurationException e) { // Do not print stack trace, a user-friendly error-message has already been logged } catch (IOException e) { // Broken pipe is expected on close, because the socket is closed by the client if (!IO.isBrokenPipe(e)) { Ln.e("Video encoding error", e); } } finally { Ln.d("Screen streaming stopped"); listener.onTerminated(true); } }, "video"); thread.start(); } @Override public void stop() { if (thread != null) { stopped.set(true); } } @Override public void join() throws InterruptedException { if (thread != null) { thread.join(); } } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/SurfaceEncoder.java
2,604
// Keep the values in descending order
line_comment
nl
package com.genymobile.scrcpy; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.os.Looper; import android.os.SystemClock; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class SurfaceEncoder implements AsyncProcessor { private static final int DEFAULT_I_FRAME_INTERVAL = 10; // seconds private static final int REPEAT_FRAME_DELAY_US = 100_000; // repeat after 100ms private static final String KEY_MAX_FPS_TO_ENCODER = "max-fps-to-encoder"; // Keep the<SUF> private static final int[] MAX_SIZE_FALLBACK = {2560, 1920, 1600, 1280, 1024, 800}; private static final int MAX_CONSECUTIVE_ERRORS = 3; private final SurfaceCapture capture; private final Streamer streamer; private final String encoderName; private final List<CodecOption> codecOptions; private final int videoBitRate; private final int maxFps; private final boolean downsizeOnError; private boolean firstFrameSent; private int consecutiveErrors; private Thread thread; private final AtomicBoolean stopped = new AtomicBoolean(); public SurfaceEncoder(SurfaceCapture capture, Streamer streamer, int videoBitRate, int maxFps, List<CodecOption> codecOptions, String encoderName, boolean downsizeOnError) { this.capture = capture; this.streamer = streamer; this.videoBitRate = videoBitRate; this.maxFps = maxFps; this.codecOptions = codecOptions; this.encoderName = encoderName; this.downsizeOnError = downsizeOnError; } private void streamScreen() throws IOException, ConfigurationException { Codec codec = streamer.getCodec(); MediaCodec mediaCodec = createMediaCodec(codec, encoderName); MediaFormat format = createFormat(codec.getMimeType(), videoBitRate, maxFps, codecOptions); capture.init(); try { streamer.writeVideoHeader(capture.getSize()); boolean alive; do { Size size = capture.getSize(); format.setInteger(MediaFormat.KEY_WIDTH, size.getWidth()); format.setInteger(MediaFormat.KEY_HEIGHT, size.getHeight()); Surface surface = null; try { mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = mediaCodec.createInputSurface(); capture.start(surface); mediaCodec.start(); alive = encode(mediaCodec, streamer); // do not call stop() on exception, it would trigger an IllegalStateException mediaCodec.stop(); } catch (IllegalStateException | IllegalArgumentException e) { Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage()); if (!prepareRetry(size)) { throw e; } Ln.i("Retrying..."); alive = true; } finally { mediaCodec.reset(); if (surface != null) { surface.release(); } } } while (alive); } finally { mediaCodec.release(); capture.release(); } } private boolean prepareRetry(Size currentSize) { if (firstFrameSent) { ++consecutiveErrors; if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) { // Definitively fail return false; } // Wait a bit to increase the probability that retrying will fix the problem SystemClock.sleep(50); return true; } if (!downsizeOnError) { // Must fail immediately return false; } // Downsizing on error is only enabled if an encoding failure occurs before the first frame (downsizing later could be surprising) int newMaxSize = chooseMaxSizeFallback(currentSize); if (newMaxSize == 0) { // Must definitively fail return false; } boolean accepted = capture.setMaxSize(newMaxSize); if (!accepted) { return false; } // Retry with a smaller size Ln.i("Retrying with -m" + newMaxSize + "..."); return true; } private static int chooseMaxSizeFallback(Size failedSize) { int currentMaxSize = Math.max(failedSize.getWidth(), failedSize.getHeight()); for (int value : MAX_SIZE_FALLBACK) { if (value < currentMaxSize) { // We found a smaller value to reduce the video size return value; } } // No fallback, fail definitively return 0; } private boolean encode(MediaCodec codec, Streamer streamer) throws IOException { boolean eof = false; boolean alive = true; MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); while (!capture.consumeReset() && !eof) { if (stopped.get()) { alive = false; break; } int outputBufferId = codec.dequeueOutputBuffer(bufferInfo, -1); try { if (capture.consumeReset()) { // must restart encoding with new size break; } eof = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0; if (outputBufferId >= 0) { ByteBuffer codecBuffer = codec.getOutputBuffer(outputBufferId); boolean isConfig = (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0; if (!isConfig) { // If this is not a config packet, then it contains a frame firstFrameSent = true; consecutiveErrors = 0; } streamer.writePacket(codecBuffer, bufferInfo); } } finally { if (outputBufferId >= 0) { codec.releaseOutputBuffer(outputBufferId, false); } } } if (capture.isClosed()) { // The capture might have been closed internally (for example if the camera is disconnected) alive = false; } return !eof && alive; } private static MediaCodec createMediaCodec(Codec codec, String encoderName) throws IOException, ConfigurationException { if (encoderName != null) { Ln.d("Creating encoder by name: '" + encoderName + "'"); try { return MediaCodec.createByCodecName(encoderName); } catch (IllegalArgumentException e) { Ln.e("Video encoder '" + encoderName + "' for " + codec.getName() + " not found\n" + LogUtils.buildVideoEncoderListMessage()); throw new ConfigurationException("Unknown encoder: " + encoderName); } catch (IOException e) { Ln.e("Could not create video encoder '" + encoderName + "' for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } try { MediaCodec mediaCodec = MediaCodec.createEncoderByType(codec.getMimeType()); Ln.d("Using video encoder: '" + mediaCodec.getName() + "'"); return mediaCodec; } catch (IOException | IllegalArgumentException e) { Ln.e("Could not create default video encoder for " + codec.getName() + "\n" + LogUtils.buildVideoEncoderListMessage()); throw e; } } private static MediaFormat createFormat(String videoMimeType, int bitRate, int maxFps, List<CodecOption> codecOptions) { MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, videoMimeType); format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate); // must be present to configure the encoder, but does not impact the actual frame rate, which is variable format.setInteger(MediaFormat.KEY_FRAME_RATE, 60); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, DEFAULT_I_FRAME_INTERVAL); // display the very first frame, and recover from bad quality when no new frames format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_FRAME_DELAY_US); // µs if (maxFps > 0) { // The key existed privately before Android 10: // <https://android.googlesource.com/platform/frameworks/base/+/625f0aad9f7a259b6881006ad8710adce57d1384%5E%21/> // <https://github.com/Genymobile/scrcpy/issues/488#issuecomment-567321437> format.setFloat(KEY_MAX_FPS_TO_ENCODER, maxFps); } if (codecOptions != null) { for (CodecOption option : codecOptions) { String key = option.getKey(); Object value = option.getValue(); CodecUtils.setCodecOption(format, key, value); Ln.d("Video codec option set: " + key + " (" + value.getClass().getSimpleName() + ") = " + value); } } return format; } @Override public void start(TerminationListener listener) { thread = new Thread(() -> { // Some devices (Meizu) deadlock if the video encoding thread has no Looper // <https://github.com/Genymobile/scrcpy/issues/4143> Looper.prepare(); try { streamScreen(); } catch (ConfigurationException e) { // Do not print stack trace, a user-friendly error-message has already been logged } catch (IOException e) { // Broken pipe is expected on close, because the socket is closed by the client if (!IO.isBrokenPipe(e)) { Ln.e("Video encoding error", e); } } finally { Ln.d("Screen streaming stopped"); listener.onTerminated(true); } }, "video"); thread.start(); } @Override public void stop() { if (thread != null) { stopped.set(true); } } @Override public void join() throws InterruptedException { if (thread != null) { thread.join(); } } }
686_5
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import static com.google.common.collect.ImmutableMapEntry.createEntryArray; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.Serializable; import java.util.IdentityHashMap; import java.util.function.BiConsumer; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Implementation of {@link ImmutableMap} used for 0 entries and for 2+ entries. Additional * implementations exist for particular cases, like {@link ImmutableTable} views and hash flooding. * (This doc discusses {@link ImmutableMap} subclasses only for the JRE flavor; the Android flavor * differs.) * * @author Jesse Wilson * @author Kevin Bourrillion * @author Gregory Kick */ @GwtCompatible(serializable = true, emulated = true) @ElementTypesAreNonnullByDefault final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> { @SuppressWarnings("unchecked") static final ImmutableMap<Object, Object> EMPTY = new RegularImmutableMap<>((Entry<Object, Object>[]) ImmutableMap.EMPTY_ENTRY_ARRAY, null, 0); /** * Closed addressing tends to perform well even with high load factors. Being conservative here * ensures that the table is still likely to be relatively sparse (hence it misses fast) while * saving space. */ @VisibleForTesting static final double MAX_LOAD_FACTOR = 1.2; /** * Maximum allowed false positive probability of detecting a hash flooding attack given random * input. */ @VisibleForTesting static final double HASH_FLOODING_FPP = 0.001; /** * Maximum allowed length of a hash table bucket before falling back to a j.u.HashMap based * implementation. Experimentally determined. */ @VisibleForTesting static final int MAX_HASH_BUCKET_LENGTH = 8; // entries in insertion order @VisibleForTesting final transient Entry<K, V>[] entries; // array of linked lists of entries @CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] table; // 'and' with an int to get a table index private final transient int mask; static <K, V> ImmutableMap<K, V> fromEntries(Entry<K, V>... entries) { return fromEntryArray(entries.length, entries, /* throwIfDuplicateKeys= */ true); } /** * Creates an ImmutableMap from the first n entries in entryArray. This implementation may replace * the entries in entryArray with its own entry objects (though they will have the same key/value * contents), and may take ownership of entryArray. */ static <K, V> ImmutableMap<K, V> fromEntryArray( int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) { checkPositionIndex(n, entryArray.length); if (n == 0) { @SuppressWarnings("unchecked") // it has no entries so the type variables don't matter ImmutableMap<K, V> empty = (ImmutableMap<K, V>) EMPTY; return empty; } try { return fromEntryArrayCheckingBucketOverflow(n, entryArray, throwIfDuplicateKeys); } catch (BucketOverflowException e) { // probable hash flooding attack, fall back to j.u.HM based implementation and use its // implementation of hash flooding protection return JdkBackedImmutableMap.create(n, entryArray, throwIfDuplicateKeys); } } private static <K, V> ImmutableMap<K, V> fromEntryArrayCheckingBucketOverflow( int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) throws BucketOverflowException { /* * The cast is safe: n==entryArray.length means that we have filled the whole array with Entry * instances, in which case it is safe to cast it from an array of nullable entries to an array * of non-null entries. */ @SuppressWarnings("nullness") Entry<K, V>[] entries = (n == entryArray.length) ? (Entry<K, V>[]) entryArray : createEntryArray(n); int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR); @Nullable ImmutableMapEntry<K, V>[] table = createEntryArray(tableSize); int mask = tableSize - 1; // If duplicates are allowed, this IdentityHashMap will record the final Entry for each // duplicated key. We will use this final Entry to overwrite earlier slots in the entries array // that have the same key. Then a second pass will remove all but the first of the slots that // have this Entry. The value in the map becomes false when this first entry has been copied, so // we know not to copy the remaining ones. IdentityHashMap<Entry<K, V>, Boolean> duplicates = null; int dupCount = 0; for (int entryIndex = n - 1; entryIndex >= 0; entryIndex--) { // requireNonNull is safe because the first `n` elements have been filled in. Entry<K, V> entry = requireNonNull(entryArray[entryIndex]); K key = entry.getKey(); V value = entry.getValue(); checkEntryNotNull(key, value); int tableIndex = Hashing.smear(key.hashCode()) & mask; ImmutableMapEntry<K, V> keyBucketHead = table[tableIndex]; ImmutableMapEntry<K, V> effectiveEntry = checkNoConflictInKeyBucket(key, value, keyBucketHead, throwIfDuplicateKeys); if (effectiveEntry == null) { // prepend, not append, so the entries can be immutable effectiveEntry = (keyBucketHead == null) ? makeImmutable(entry, key, value) : new NonTerminalImmutableMapEntry<K, V>(key, value, keyBucketHead); table[tableIndex] = effectiveEntry; } else { // We already saw this key, and the first value we saw (going backwards) is the one we are // keeping. So we won't touch table[], but we do still want to add the existing entry that // we found to entries[] so that we will see this key in the right place when iterating. if (duplicates == null) { duplicates = new IdentityHashMap<>(); } duplicates.put(effectiveEntry, true); dupCount++; // Make sure we are not overwriting the original entries array, in case we later do // buildOrThrow(). We would want an exception to include two values for the duplicate key. if (entries == entryArray) { // Temporary variable is necessary to defeat bad smartcast (entries adopting the type of // entryArray) in the Kotlin translation. Entry<K, V>[] originalEntries = entries; entries = originalEntries.clone(); } } entries[entryIndex] = effectiveEntry; } if (duplicates != null) { // Explicit type parameters needed here to avoid a problem with nullness inference. entries = RegularImmutableMap.<K, V>removeDuplicates(entries, n, n - dupCount, duplicates); int newTableSize = Hashing.closedTableSize(entries.length, MAX_LOAD_FACTOR); if (newTableSize != tableSize) { return fromEntryArrayCheckingBucketOverflow( entries.length, entries, /* throwIfDuplicateKeys= */ true); } } return new RegularImmutableMap<>(entries, table, mask); } /** * Constructs a new entry array where each duplicated key from the original appears only once, at * its first position but with its final value. The {@code duplicates} map is modified. * * @param entries the original array of entries including duplicates * @param n the number of valid entries in {@code entries} * @param newN the expected number of entries once duplicates are removed * @param duplicates a map of canonical {@link Entry} objects for each duplicate key. This map * will be updated by the method, setting each value to false as soon as the {@link Entry} has * been included in the new entry array. * @return an array of {@code newN} entries where no key appears more than once. */ static <K, V> Entry<K, V>[] removeDuplicates( Entry<K, V>[] entries, int n, int newN, IdentityHashMap<Entry<K, V>, Boolean> duplicates) { Entry<K, V>[] newEntries = createEntryArray(newN); for (int in = 0, out = 0; in < n; in++) { Entry<K, V> entry = entries[in]; Boolean status = duplicates.get(entry); // null=>not dup'd; true=>dup'd, first; false=>dup'd, not first if (status != null) { if (status) { duplicates.put(entry, false); } else { continue; // delete this entry; we already copied an earlier one for the same key } } newEntries[out++] = entry; } return newEntries; } /** Makes an entry usable internally by a new ImmutableMap without rereading its contents. */ static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) { boolean reusable = entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable(); return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value); } /** Makes an entry usable internally by a new ImmutableMap. */ static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) { return makeImmutable(entry, entry.getKey(), entry.getValue()); } private RegularImmutableMap( Entry<K, V>[] entries, @CheckForNull @Nullable ImmutableMapEntry<K, V>[] table, int mask) { this.entries = entries; this.table = table; this.mask = mask; } /** * Checks if the given key already appears in the hash chain starting at {@code keyBucketHead}. If * it does not, then null is returned. If it does, then if {@code throwIfDuplicateKeys} is true an * {@code IllegalArgumentException} is thrown, and otherwise the existing {@link Entry} is * returned. * * @throws IllegalArgumentException if another entry in the bucket has the same key and {@code * throwIfDuplicateKeys} is true * @throws BucketOverflowException if this bucket has too many entries, which may indicate a hash * flooding attack */ @CanIgnoreReturnValue @CheckForNull static <K, V> ImmutableMapEntry<K, V> checkNoConflictInKeyBucket( Object key, Object newValue, @CheckForNull ImmutableMapEntry<K, V> keyBucketHead, boolean throwIfDuplicateKeys) throws BucketOverflowException { int bucketSize = 0; for (; keyBucketHead != null; keyBucketHead = keyBucketHead.getNextInKeyBucket()) { if (keyBucketHead.getKey().equals(key)) { if (throwIfDuplicateKeys) { checkNoConflict(/* safe= */ false, "key", keyBucketHead, key + "=" + newValue); } else { return keyBucketHead; } } if (++bucketSize > MAX_HASH_BUCKET_LENGTH) { throw new BucketOverflowException(); } } return null; } static class BucketOverflowException extends Exception {} @Override @CheckForNull public V get(@CheckForNull Object key) { return get(key, table, mask); } @CheckForNull static <V> V get( @CheckForNull Object key, @CheckForNull @Nullable ImmutableMapEntry<?, V>[] keyTable, int mask) { if (key == null || keyTable == null) { return null; } int index = Hashing.smear(key.hashCode()) & mask; for (ImmutableMapEntry<?, V> entry = keyTable[index]; entry != null; entry = entry.getNextInKeyBucket()) { Object candidateKey = entry.getKey(); /* * Assume that equals uses the == optimization when appropriate, and that * it would check hash codes as an optimization when appropriate. If we * did these things, it would just make things worse for the most * performance-conscious users. */ if (key.equals(candidateKey)) { return entry.getValue(); } } return null; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { checkNotNull(action); for (Entry<K, V> entry : entries) { action.accept(entry.getKey(), entry.getValue()); } } @Override public int size() { return entries.length; } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries); } @Override ImmutableSet<K> createKeySet() { return new KeySet<>(this); } @GwtCompatible(emulated = true) private static final class KeySet<K> extends IndexedImmutableSet<K> { private final RegularImmutableMap<K, ?> map; KeySet(RegularImmutableMap<K, ?> map) { this.map = map; } @Override K get(int index) { return map.entries[index].getKey(); } @Override public boolean contains(@CheckForNull Object object) { return map.containsKey(object); } @Override boolean isPartialView() { return true; } @Override public int size() { return map.size(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // No longer used for new writes, but kept so that old data can still be read. @GwtIncompatible // serialization @J2ktIncompatible @SuppressWarnings("unused") private static class SerializedForm<K> implements Serializable { final ImmutableMap<K, ?> map; SerializedForm(ImmutableMap<K, ?> map) { this.map = map; } Object readResolve() { return map.keySet(); } @J2ktIncompatible // serialization private static final long serialVersionUID = 0; } } @Override ImmutableCollection<V> createValues() { return new Values<>(this); } @GwtCompatible(emulated = true) private static final class Values<K, V> extends ImmutableList<V> { final RegularImmutableMap<K, V> map; Values(RegularImmutableMap<K, V> map) { this.map = map; } @Override public V get(int index) { return map.entries[index].getValue(); } @Override public int size() { return map.size(); } @Override boolean isPartialView() { return true; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // No longer used for new writes, but kept so that old data can still be read. @GwtIncompatible // serialization @J2ktIncompatible @SuppressWarnings("unused") private static class SerializedForm<V> implements Serializable { final ImmutableMap<?, V> map; SerializedForm(ImmutableMap<?, V> map) { this.map = map; } Object readResolve() { return map.values(); } @J2ktIncompatible // serialization private static final long serialVersionUID = 0; } } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // This class is never actually serialized directly, but we have to make the // warning go away (and suppressing would suppress for all nested classes too) @J2ktIncompatible // serialization private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/collect/RegularImmutableMap.java
4,403
// entries in insertion order
line_comment
nl
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import static com.google.common.collect.ImmutableMapEntry.createEntryArray; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.Serializable; import java.util.IdentityHashMap; import java.util.function.BiConsumer; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Implementation of {@link ImmutableMap} used for 0 entries and for 2+ entries. Additional * implementations exist for particular cases, like {@link ImmutableTable} views and hash flooding. * (This doc discusses {@link ImmutableMap} subclasses only for the JRE flavor; the Android flavor * differs.) * * @author Jesse Wilson * @author Kevin Bourrillion * @author Gregory Kick */ @GwtCompatible(serializable = true, emulated = true) @ElementTypesAreNonnullByDefault final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> { @SuppressWarnings("unchecked") static final ImmutableMap<Object, Object> EMPTY = new RegularImmutableMap<>((Entry<Object, Object>[]) ImmutableMap.EMPTY_ENTRY_ARRAY, null, 0); /** * Closed addressing tends to perform well even with high load factors. Being conservative here * ensures that the table is still likely to be relatively sparse (hence it misses fast) while * saving space. */ @VisibleForTesting static final double MAX_LOAD_FACTOR = 1.2; /** * Maximum allowed false positive probability of detecting a hash flooding attack given random * input. */ @VisibleForTesting static final double HASH_FLOODING_FPP = 0.001; /** * Maximum allowed length of a hash table bucket before falling back to a j.u.HashMap based * implementation. Experimentally determined. */ @VisibleForTesting static final int MAX_HASH_BUCKET_LENGTH = 8; // entries in<SUF> @VisibleForTesting final transient Entry<K, V>[] entries; // array of linked lists of entries @CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] table; // 'and' with an int to get a table index private final transient int mask; static <K, V> ImmutableMap<K, V> fromEntries(Entry<K, V>... entries) { return fromEntryArray(entries.length, entries, /* throwIfDuplicateKeys= */ true); } /** * Creates an ImmutableMap from the first n entries in entryArray. This implementation may replace * the entries in entryArray with its own entry objects (though they will have the same key/value * contents), and may take ownership of entryArray. */ static <K, V> ImmutableMap<K, V> fromEntryArray( int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) { checkPositionIndex(n, entryArray.length); if (n == 0) { @SuppressWarnings("unchecked") // it has no entries so the type variables don't matter ImmutableMap<K, V> empty = (ImmutableMap<K, V>) EMPTY; return empty; } try { return fromEntryArrayCheckingBucketOverflow(n, entryArray, throwIfDuplicateKeys); } catch (BucketOverflowException e) { // probable hash flooding attack, fall back to j.u.HM based implementation and use its // implementation of hash flooding protection return JdkBackedImmutableMap.create(n, entryArray, throwIfDuplicateKeys); } } private static <K, V> ImmutableMap<K, V> fromEntryArrayCheckingBucketOverflow( int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) throws BucketOverflowException { /* * The cast is safe: n==entryArray.length means that we have filled the whole array with Entry * instances, in which case it is safe to cast it from an array of nullable entries to an array * of non-null entries. */ @SuppressWarnings("nullness") Entry<K, V>[] entries = (n == entryArray.length) ? (Entry<K, V>[]) entryArray : createEntryArray(n); int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR); @Nullable ImmutableMapEntry<K, V>[] table = createEntryArray(tableSize); int mask = tableSize - 1; // If duplicates are allowed, this IdentityHashMap will record the final Entry for each // duplicated key. We will use this final Entry to overwrite earlier slots in the entries array // that have the same key. Then a second pass will remove all but the first of the slots that // have this Entry. The value in the map becomes false when this first entry has been copied, so // we know not to copy the remaining ones. IdentityHashMap<Entry<K, V>, Boolean> duplicates = null; int dupCount = 0; for (int entryIndex = n - 1; entryIndex >= 0; entryIndex--) { // requireNonNull is safe because the first `n` elements have been filled in. Entry<K, V> entry = requireNonNull(entryArray[entryIndex]); K key = entry.getKey(); V value = entry.getValue(); checkEntryNotNull(key, value); int tableIndex = Hashing.smear(key.hashCode()) & mask; ImmutableMapEntry<K, V> keyBucketHead = table[tableIndex]; ImmutableMapEntry<K, V> effectiveEntry = checkNoConflictInKeyBucket(key, value, keyBucketHead, throwIfDuplicateKeys); if (effectiveEntry == null) { // prepend, not append, so the entries can be immutable effectiveEntry = (keyBucketHead == null) ? makeImmutable(entry, key, value) : new NonTerminalImmutableMapEntry<K, V>(key, value, keyBucketHead); table[tableIndex] = effectiveEntry; } else { // We already saw this key, and the first value we saw (going backwards) is the one we are // keeping. So we won't touch table[], but we do still want to add the existing entry that // we found to entries[] so that we will see this key in the right place when iterating. if (duplicates == null) { duplicates = new IdentityHashMap<>(); } duplicates.put(effectiveEntry, true); dupCount++; // Make sure we are not overwriting the original entries array, in case we later do // buildOrThrow(). We would want an exception to include two values for the duplicate key. if (entries == entryArray) { // Temporary variable is necessary to defeat bad smartcast (entries adopting the type of // entryArray) in the Kotlin translation. Entry<K, V>[] originalEntries = entries; entries = originalEntries.clone(); } } entries[entryIndex] = effectiveEntry; } if (duplicates != null) { // Explicit type parameters needed here to avoid a problem with nullness inference. entries = RegularImmutableMap.<K, V>removeDuplicates(entries, n, n - dupCount, duplicates); int newTableSize = Hashing.closedTableSize(entries.length, MAX_LOAD_FACTOR); if (newTableSize != tableSize) { return fromEntryArrayCheckingBucketOverflow( entries.length, entries, /* throwIfDuplicateKeys= */ true); } } return new RegularImmutableMap<>(entries, table, mask); } /** * Constructs a new entry array where each duplicated key from the original appears only once, at * its first position but with its final value. The {@code duplicates} map is modified. * * @param entries the original array of entries including duplicates * @param n the number of valid entries in {@code entries} * @param newN the expected number of entries once duplicates are removed * @param duplicates a map of canonical {@link Entry} objects for each duplicate key. This map * will be updated by the method, setting each value to false as soon as the {@link Entry} has * been included in the new entry array. * @return an array of {@code newN} entries where no key appears more than once. */ static <K, V> Entry<K, V>[] removeDuplicates( Entry<K, V>[] entries, int n, int newN, IdentityHashMap<Entry<K, V>, Boolean> duplicates) { Entry<K, V>[] newEntries = createEntryArray(newN); for (int in = 0, out = 0; in < n; in++) { Entry<K, V> entry = entries[in]; Boolean status = duplicates.get(entry); // null=>not dup'd; true=>dup'd, first; false=>dup'd, not first if (status != null) { if (status) { duplicates.put(entry, false); } else { continue; // delete this entry; we already copied an earlier one for the same key } } newEntries[out++] = entry; } return newEntries; } /** Makes an entry usable internally by a new ImmutableMap without rereading its contents. */ static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) { boolean reusable = entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable(); return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value); } /** Makes an entry usable internally by a new ImmutableMap. */ static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) { return makeImmutable(entry, entry.getKey(), entry.getValue()); } private RegularImmutableMap( Entry<K, V>[] entries, @CheckForNull @Nullable ImmutableMapEntry<K, V>[] table, int mask) { this.entries = entries; this.table = table; this.mask = mask; } /** * Checks if the given key already appears in the hash chain starting at {@code keyBucketHead}. If * it does not, then null is returned. If it does, then if {@code throwIfDuplicateKeys} is true an * {@code IllegalArgumentException} is thrown, and otherwise the existing {@link Entry} is * returned. * * @throws IllegalArgumentException if another entry in the bucket has the same key and {@code * throwIfDuplicateKeys} is true * @throws BucketOverflowException if this bucket has too many entries, which may indicate a hash * flooding attack */ @CanIgnoreReturnValue @CheckForNull static <K, V> ImmutableMapEntry<K, V> checkNoConflictInKeyBucket( Object key, Object newValue, @CheckForNull ImmutableMapEntry<K, V> keyBucketHead, boolean throwIfDuplicateKeys) throws BucketOverflowException { int bucketSize = 0; for (; keyBucketHead != null; keyBucketHead = keyBucketHead.getNextInKeyBucket()) { if (keyBucketHead.getKey().equals(key)) { if (throwIfDuplicateKeys) { checkNoConflict(/* safe= */ false, "key", keyBucketHead, key + "=" + newValue); } else { return keyBucketHead; } } if (++bucketSize > MAX_HASH_BUCKET_LENGTH) { throw new BucketOverflowException(); } } return null; } static class BucketOverflowException extends Exception {} @Override @CheckForNull public V get(@CheckForNull Object key) { return get(key, table, mask); } @CheckForNull static <V> V get( @CheckForNull Object key, @CheckForNull @Nullable ImmutableMapEntry<?, V>[] keyTable, int mask) { if (key == null || keyTable == null) { return null; } int index = Hashing.smear(key.hashCode()) & mask; for (ImmutableMapEntry<?, V> entry = keyTable[index]; entry != null; entry = entry.getNextInKeyBucket()) { Object candidateKey = entry.getKey(); /* * Assume that equals uses the == optimization when appropriate, and that * it would check hash codes as an optimization when appropriate. If we * did these things, it would just make things worse for the most * performance-conscious users. */ if (key.equals(candidateKey)) { return entry.getValue(); } } return null; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { checkNotNull(action); for (Entry<K, V> entry : entries) { action.accept(entry.getKey(), entry.getValue()); } } @Override public int size() { return entries.length; } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries); } @Override ImmutableSet<K> createKeySet() { return new KeySet<>(this); } @GwtCompatible(emulated = true) private static final class KeySet<K> extends IndexedImmutableSet<K> { private final RegularImmutableMap<K, ?> map; KeySet(RegularImmutableMap<K, ?> map) { this.map = map; } @Override K get(int index) { return map.entries[index].getKey(); } @Override public boolean contains(@CheckForNull Object object) { return map.containsKey(object); } @Override boolean isPartialView() { return true; } @Override public int size() { return map.size(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // No longer used for new writes, but kept so that old data can still be read. @GwtIncompatible // serialization @J2ktIncompatible @SuppressWarnings("unused") private static class SerializedForm<K> implements Serializable { final ImmutableMap<K, ?> map; SerializedForm(ImmutableMap<K, ?> map) { this.map = map; } Object readResolve() { return map.keySet(); } @J2ktIncompatible // serialization private static final long serialVersionUID = 0; } } @Override ImmutableCollection<V> createValues() { return new Values<>(this); } @GwtCompatible(emulated = true) private static final class Values<K, V> extends ImmutableList<V> { final RegularImmutableMap<K, V> map; Values(RegularImmutableMap<K, V> map) { this.map = map; } @Override public V get(int index) { return map.entries[index].getValue(); } @Override public int size() { return map.size(); } @Override boolean isPartialView() { return true; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // No longer used for new writes, but kept so that old data can still be read. @GwtIncompatible // serialization @J2ktIncompatible @SuppressWarnings("unused") private static class SerializedForm<V> implements Serializable { final ImmutableMap<?, V> map; SerializedForm(ImmutableMap<?, V> map) { this.map = map; } Object readResolve() { return map.values(); } @J2ktIncompatible // serialization private static final long serialVersionUID = 0; } } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } // This class is never actually serialized directly, but we have to make the // warning go away (and suppressing would suppress for all nested classes too) @J2ktIncompatible // serialization private static final long serialVersionUID = 0; }
703_31
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; import core.Tuple; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes interencounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone); if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. * @see #SECONDS_IN_UNIT_S */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for(Connection con : getHost()) { // for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
knightcode/the-one-pitt
routing/ProphetRouterWithEstimation.java
4,701
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
line_comment
nl
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; import core.Tuple; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes interencounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t<SUF> if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. * @see #SECONDS_IN_UNIT_S */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for(Connection con : getHost()) { // for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
709_0
package nl.openconvert.tei; import java.util.List; import nl.openconvert.util.XML; import org.w3c.dom.Element; public class Paragraph { public String id = null; boolean decent=true; public int numTokens=-1; public Paragraph(Element p) { this.id = p.getAttribute("id"); if (this.id==null) this.id = p.getAttribute("xml:id"); String s = p.getTextContent(); String[] tokens = s.split("\\s+"); this.numTokens = tokens.length; } /** * Een heuristiekje om de meest verknipte alinea's uit te sluiten. * Voorlopig ook de alinea's met andere dan NE tags eruit gooien omdat de attestatie tool * niet zo van die tagjes houdt en ik dan gewoon de hele inhoud van de p kan vervangen? * @param p * @return */ public static boolean isDecentParagraph(Element p) { String s = p.getTextContent(); boolean startsOK = s.matches("^\\s*\\p{P}*\\s*\\p{Lu}.*"); boolean endsOK = s.matches(".*[.?!]\\p{P}*\\s*$"); List<Element> subElements = XML.getAllSubelements(p, true); boolean subsOK=true; for (Element e: subElements) { String n = e.getNodeName(); if (! (n.contains("Name") || n.contains("name"))) { subsOK=false; } } return (subsOK && startsOK && endsOK); } }
INL/OpenConvert
src/nl/openconvert/tei/Paragraph.java
424
/** * Een heuristiekje om de meest verknipte alinea's uit te sluiten. * Voorlopig ook de alinea's met andere dan NE tags eruit gooien omdat de attestatie tool * niet zo van die tagjes houdt en ik dan gewoon de hele inhoud van de p kan vervangen? * @param p * @return */
block_comment
nl
package nl.openconvert.tei; import java.util.List; import nl.openconvert.util.XML; import org.w3c.dom.Element; public class Paragraph { public String id = null; boolean decent=true; public int numTokens=-1; public Paragraph(Element p) { this.id = p.getAttribute("id"); if (this.id==null) this.id = p.getAttribute("xml:id"); String s = p.getTextContent(); String[] tokens = s.split("\\s+"); this.numTokens = tokens.length; } /** * Een heuristiekje om<SUF>*/ public static boolean isDecentParagraph(Element p) { String s = p.getTextContent(); boolean startsOK = s.matches("^\\s*\\p{P}*\\s*\\p{Lu}.*"); boolean endsOK = s.matches(".*[.?!]\\p{P}*\\s*$"); List<Element> subElements = XML.getAllSubelements(p, true); boolean subsOK=true; for (Element e: subElements) { String n = e.getNodeName(); if (! (n.contains("Name") || n.contains("name"))) { subsOK=false; } } return (subsOK && startsOK && endsOK); } }
712_0
package com.hartwig.hmftools.patientdb.clinical.lims; import com.hartwig.hmftools.patientdb.clinical.lims.cohort.LimsCohortConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public enum LimsGermlineReportingLevel { REPORT_WITH_NOTIFICATION, REPORT_WITHOUT_NOTIFICATION, NO_REPORTING; @NotNull static LimsGermlineReportingLevel fromLimsInputs(boolean limsSampleReportGermlineVariants, @NotNull String germlineReportingLevelString, @NotNull String sampleId, @Nullable LimsCohortConfig cohort) { if (limsSampleReportGermlineVariants && cohort != null) { // Cases "geen toevalsbevindingen: familie mag deze/wel niet opvragen" have been merged // into a single category "geen toevalsbevindingen" per feb 1st 2020 if (cohort.reportGermline() && cohort.reportGermlineFlag()) { switch (germlineReportingLevelString) { case "1: Behandelbare toevalsbevindingen": case "2: Alle toevalsbevindingen": case "1: Yes": return REPORT_WITH_NOTIFICATION; case "3: Geen toevalsbevindingen": case "3: Geen toevalsbevindingen; familie mag deze wel opvragen": case "4: Geen toevalsbevindingen; familie mag deze niet opvragen": case "2: No": return REPORT_WITHOUT_NOTIFICATION; default: throw new IllegalStateException( "Cannot resolve germline reporting choice " + germlineReportingLevelString + " for sample " + sampleId); } } else if (cohort.reportGermline() && !cohort.reportGermlineFlag()) { return REPORT_WITHOUT_NOTIFICATION; } } return NO_REPORTING; } }
hartwigmedical/hmftools
patient-db/src/main/java/com/hartwig/hmftools/patientdb/clinical/lims/LimsGermlineReportingLevel.java
454
// Cases "geen toevalsbevindingen: familie mag deze/wel niet opvragen" have been merged
line_comment
nl
package com.hartwig.hmftools.patientdb.clinical.lims; import com.hartwig.hmftools.patientdb.clinical.lims.cohort.LimsCohortConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public enum LimsGermlineReportingLevel { REPORT_WITH_NOTIFICATION, REPORT_WITHOUT_NOTIFICATION, NO_REPORTING; @NotNull static LimsGermlineReportingLevel fromLimsInputs(boolean limsSampleReportGermlineVariants, @NotNull String germlineReportingLevelString, @NotNull String sampleId, @Nullable LimsCohortConfig cohort) { if (limsSampleReportGermlineVariants && cohort != null) { // Cases "geen<SUF> // into a single category "geen toevalsbevindingen" per feb 1st 2020 if (cohort.reportGermline() && cohort.reportGermlineFlag()) { switch (germlineReportingLevelString) { case "1: Behandelbare toevalsbevindingen": case "2: Alle toevalsbevindingen": case "1: Yes": return REPORT_WITH_NOTIFICATION; case "3: Geen toevalsbevindingen": case "3: Geen toevalsbevindingen; familie mag deze wel opvragen": case "4: Geen toevalsbevindingen; familie mag deze niet opvragen": case "2: No": return REPORT_WITHOUT_NOTIFICATION; default: throw new IllegalStateException( "Cannot resolve germline reporting choice " + germlineReportingLevelString + " for sample " + sampleId); } } else if (cohort.reportGermline() && !cohort.reportGermlineFlag()) { return REPORT_WITHOUT_NOTIFICATION; } } return NO_REPORTING; } }
715_3
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd in de oude versie ook niet gedaan. runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte test op Total; dit gaat mis if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] = regel[0].replace("'", ""); for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
sdcTools/tauargus
src/tauargus/model/LinkedTables.java
7,856
//checkHierarchies werd in de oude versie ook niet gedaan.
line_comment
nl
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd<SUF> runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte test op Total; dit gaat mis if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] = regel[0].replace("'", ""); for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
715_6
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd in de oude versie ook niet gedaan. runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte test op Total; dit gaat mis if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] = regel[0].replace("'", ""); for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
sdcTools/tauargus
src/tauargus/model/LinkedTables.java
7,856
//TODO echte test op Total; dit gaat mis
line_comment
nl
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd in de oude versie ook niet gedaan. runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte<SUF> if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] = regel[0].replace("'", ""); for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
715_33
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd in de oude versie ook niet gedaan. runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte test op Total; dit gaat mis if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] = regel[0].replace("'", ""); for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
sdcTools/tauargus
src/tauargus/model/LinkedTables.java
7,856
// regel[0] = regel[0].replace("'", "");
line_comment
nl
/* * Argus Open Source * Software to apply Statistical Disclosure Control techniques * * Copyright 2014 Statistics Netherlands * * This program is free software; you can redistribute it and/or * modify it under the terms of the European Union Public Licence * (EUPL) version 1.1, as published by the European Commission. * * You can find the text of the EUPL v1.1 on * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * This software is distributed on an "AS IS" basis without * warranties or conditions of any kind, either express or implied. */ package tauargus.model; import argus.utils.SystemUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; import tauargus.extern.dataengine.TauArgus; import tauargus.gui.DialogLinkedTables; import tauargus.service.TableService; import tauargus.utils.ExecUtils; import tauargus.utils.TauArgusUtils; /** * * @author Hundepool */ public class LinkedTables { public static String[] coverVariablesName; public static int[] coverVariablesIndex; public static int[] coverSourceTab; public static int[] coverVarSize; public static int[][] toCoverIndex; public static int coverDim; static String[][] coverCodelist; static int maxCoverCodeList; private static int[][] volgNoCL; private static final String nullen = "00000000"; private static final TauArgus tauArgus = Application.getTauArgusDll(); public static boolean TestLinkedPossible()throws ArgusException{ int i; String respVar0Name; if( TableService.numberOfTables() < 2) {throw new ArgusException ("For linked tables at least 2 tables are needed");} respVar0Name= TableService.getTable(0).respVar.name; for (i=1;i<TableService.numberOfTables();i++){ if (!respVar0Name.equals(TableService.getTable(i).respVar.name)){ throw new ArgusException ("For linked tables the same respons variable is needed"); } } return true; } public static boolean runLinkedModular(DialogLinkedTables Moeder, double MSC, double LM, double UM) throws ArgusException{ String hs = ""; int i,j; TableSet tableSet0, tableSet; Date startDate = new Date(); if (coverDim > 10){ throw new ArgusException ("The total number of explanatory variables for the Modular approach should not exceed 10"); } for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + ": "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables." + hs); tableSet0 = TableService.getTable(0); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); j = tableSet.expVar.size(); if (j > 4) { throw new ArgusException ("The max. dimension of the individual tables must not exceed 4"); } TableService.undoSuppress(i); tableSet.singletonSingletonCheck = tableSet0.singletonSingletonCheck; tableSet.singletonMultipleCheck = tableSet0.singletonMultipleCheck; tableSet.minFreqCheck = tableSet0.minFreqCheck; tableSet.maxHitasTime = tableSet0.maxHitasTime; } checkCodeList(); //checkCodeLists //prepareLinked exportTables(MSC, LM, UM);//exportTables //checkHierarchies werd in de oude versie ook niet gedaan. runCoverTable(); readResultsBack(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries()+ " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of modular linked tables procedure\n"+ TableService.numberOfTables()+" tables.\n" + hs + "Processing time: " + diff + " seconds"); return true; } static void readResultsBack()throws ArgusException{ // in fact we convert the output into aprory files and run them int[] codeIndex = new int[coverDim]; int j; TableSet tableSet; String[] codes = new String[coverDim]; String[] totCodes = new String[coverDim]; String[] regel = new String[1]; Boolean Oke; if (!TauArgusUtils.ExistFile(Application.getTempFile("tempTot.txt"))){ throw new ArgusException("The results of the protection of the cover table could not be found");} for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"" + coverCodelist[j][0] +"\"" ;} //for (j=0;j<coverDim;j++){codeIndex[j] = -1; totCodes[j] = "\"Total\"" ;} for (j=0;j<tableSet.expVar.size();j++) {codeIndex[toCoverIndex[i][j]]=toCoverIndex[i][j];} BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("temp"+i+".hst"))); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("tempTot.txt"))); regel[0] = in.readLine(); while (regel[0] != null){ if (regel[0].endsWith(",12")){ //secondary found Oke = true; for (j=0;j<coverDim;j++){ codes[j] = TauArgusUtils.GetSimpleSepToken(regel, ","); //TODO echte test op Total; dit gaat mis if ((codeIndex[j] == -1) && ((!codes[j].equals("\"\""))&&!codes[j].equals(totCodes[j]))) {Oke = false;} //retain total code of not relevant variables } if (Oke) { // for (j=0;j<tableSet.expVar.size();j++) {out.write ("\""+ codes[toCoverIndex[i][j]]+ "\";");} for (j=0;j<tableSet.expVar.size();j++) { if (codes[toCoverIndex[i][j]].equals("\"Total\"")){ out.write("\"\";"); } else { out.write (codes[toCoverIndex[i][j]]+ ";"); }} out.write("ml"); out.newLine(); } } regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError retrieving the results of modular "+(i+1) );} } // Apriory files have been made. Read them back for (int i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.suppressINFO = OptiSuppress.ReadHitasINFO("hitas.log"); tableSet.solverUsed = Application.solverSelected; int[][] aPrioryStatus = new int[5][2]; if (TableSet.processAprioryFile(Application.getTempFile("temp"+i+".hst"), i, ";", true, false, false, aPrioryStatus)!=0){ TableService.undoSuppress(i); throw new ArgusException("Error retrieving linked suppression pattern for table "+(i+1)); } else { // tableSet.nSecond = NSec[0]; tableSet.suppressed = TableSet.SUP_HITAS; tableSet.nSecond = aPrioryStatus[1][0]; } } } static void runCoverTable()throws ArgusException{ String appDir; ArrayList<String> commandline = new ArrayList<>(); //java -jar "D:\TauJava\tauargus\dist\TauArgus.jar" "C:\Users\ahnl\AppData\Local\Temp\tempTot.arb" //hs = "java -jar \""; try{ appDir = SystemUtils.getApplicationDirectory(LinkedTables.class).toString(); } catch (Exception ex){ throw new ArgusException(ex.getMessage()+"\nError running the cover table:\nCan't find TauArgus.jar");} //hs = hs + appDir + "/TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb") + "\""; commandline.add("java"); commandline.add("-jar"); commandline.add(appDir+"/TauArgus.jar"); commandline.add(Application.getTempFile("tempTot.arb")); if (Application.batchType() != Application.BATCH_COMMANDLINE) {//hs = hs + " /v";} commandline.add("/v"); } TauArgusUtils.writeBatchFileForExec( "TempTot", commandline); SystemUtils.writeLogbook("Start of the Tau-Argus procedure for the modular linked tables procedure"); int result = ExecUtils.execCommand(commandline, null, false, "Run cover table"); if (result != 0) { throw new ArgusException("Error running the cover table\nReturned value: "+result);} } static void exportTables(double MSC, double LM, double UM)throws ArgusException{ // write intermedaite files fro each table temp+i+.tab // then merge them into one file tempTot.tab // Then write the corresponding metadata file int i, j; TableSet tableSet; String regelOut; String[] codes = new String[coverDim];String [] regel = new String[1]; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); try{ tableSet.write(Application.getTempFile("temp"+i+".tab"), false, false, false, false, false, null);} catch (Exception ex){ throw new ArgusException (ex.getMessage()+ "\nError writing intermediate table "+(i+1) ); } } try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.tab"))); for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+i+".tab"))); for (j=0;j<coverDim;j++){codes[j] = "\"\"";} regel[0] = in.readLine(); while (regel[0] != null){ regelOut = ""; for(j=0;j<tableSet.expVar.size();j++){ codes[toCoverIndex[i][j]] = TauArgusUtils.GetSimpleSepToken(regel, ";"); } for(j=0;j<coverDim;j++){ regelOut = regelOut + codes[j] + ";"; } regelOut = regelOut + regel[0]; regel[0] = in.readLine(); out.write(regelOut); out.newLine(); } in.close(); } out.close(); // now the RDA file BufferedWriter rda = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.rda"))); tableSet = TableService.getTable(0); rda.write("<SEPARATOR> \";\""); rda.newLine(); for (i=0;i<coverDim;i++){ j=coverSourceTab[i]; BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp"+j+".rda"))); regelOut = in.readLine(); // This assumes that the name of a variable does not appear in any text before the definition of the variable while (regelOut.indexOf(coverVariablesName[i],0) == -1) {regelOut = in.readLine();} rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); while (regelOut.indexOf("<",0) != -1) { rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); } BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("temp0.rda"))); regelOut = in.readLine(); while (regelOut.indexOf(tableSet.respVar.name,0) == -1) {regelOut = in.readLine();} while (regelOut != null){ rda.write(regelOut); rda.newLine(); regelOut = in.readLine(); } in.close(); rda.close(); // and now the batchfile out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.arb"))); out.write("<OPENTABLEDATA> \""+ Application.getTempFile("tempTot.tab")+"\""); out.newLine(); out.write("<OPENMETADATA> \""+ Application.getTempFile("tempTot.rda")+"\""); out.newLine(); out.write("<SPECIFYTABLE> "); for (j=0;j<coverDim;j++) {out.write("\""+coverVariablesName[j]+"\"");} String hs = "|\""+tableSet.respVar.name+"\""; out.write(hs+hs); if (testDistFunction()){ out.write("|\"-3\"");} else {out.write(hs);} out.newLine(); out.write("<SAFETYRULE>"); out.newLine(); out.write("<COVER>"); out.newLine(); out.write("<READTABLE>"); out.newLine(); out.write("<SUPPRESS> MOD(1, " + Application.generalMaxHitasTime + ", "); hs = "0"; if (tableSet.singletonSingletonCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.singletonMultipleCheck){hs = "1";} out.write( hs+", "); hs = "0"; if (tableSet.minFreqCheck){hs = "1";} out.write( hs); //if (tableSet.maxScaleCost != 20000){ // out.write (", "+tableSet.maxScaleCost); //} out.write(", "+ String.valueOf(MSC)); // Always write, even when default out.write(", " + String.valueOf(LM)); out.write(", " + String.valueOf(UM)); out.write (")"); out.newLine(); out.write("<WRITETABLE> (1, 3, AS+,\""+Application.getTempFile("tempTot.txt")+"\")"); out.newLine(); out.close(); TauArgusUtils.DeleteFile(Application.getTempFile("tempTot.txt")); // out = new BufferedWriter(new FileWriter(Application.getTempFile("tempTot.bat"))); // out.write("java -jar \"D:\\TauJava\\tauargus\\dist\\TauArgus.jar\" \"" + Application.getTempFile("tempTot.arb")+ "\""); out.newLine(); // out.write ("pause"); out.newLine(); // out.close(); } catch (Exception ex){throw new ArgusException (ex.getMessage()+ "\nError writing cover table");} } private static boolean testDistFunction(){ int i; boolean b = false; TableSet tableSet; for (i=0;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); if (tableSet.costFunc == TableSet.COST_DIST){ b = true;} } return b; } public static boolean runLinkedGHMiter() throws ArgusException{ int i, returnVal;TableSet tableSet0,tableSet; String hs; Date startDate = new Date(); hs = ""; for (i=0;i<TableService.numberOfTables();i++){ hs = hs + "\n"+ (i+1) + " "+ TableService.getTableDescription(TableService.getTable(i)); } SystemUtils.writeLogbook("Start of Hypercube linked tables procedure\n"+ TableService.numberOfTables()+" tables" + hs); checkCodeList(); //checkCodeLists //prepareLinked //Write all EINGABEs for (i=0;i<TableService.numberOfTables();i++){ TableService.undoSuppress(i); returnVal=tauArgus.WriteGHMITERDataCell(Application.getTempFile("EINGABEAJ"+(i+1)+".TMP"), i, false); if (!(returnVal == 1)) { // Something wrong writing EINGABE throw new ArgusException( "Unable to write the file EINGABE for the table "+(i+1));} } //copy GHMiter parameters to other table (The dialog fills table 0, as does the batch command tableSet0 = TableService.getTable(0); for (i=1;i<TableService.numberOfTables();i++){ tableSet = TableService.getTable(i); tableSet.ratio = tableSet0.ratio; tableSet.ghMiterSize = tableSet0.ghMiterSize; tableSet.ghMiterApplySingleton = tableSet0.ghMiterApplySingleton; tableSet.ghMiterApriory =tableSet0.ghMiterApriory; tableSet.ghMiterAprioryPercentage = tableSet0.ghMiterAprioryPercentage; tableSet.ghMiterSubcode = tableSet0.ghMiterSubcode; tableSet.ghMiterSubtable = tableSet0.ghMiterSubtable; } for (i=0;i<TableService.numberOfTables();i++){ GHMiter.SchrijfSTEUER(i, "AJ"+(i+1)); tableSet=TableService.getTable(i); GHMiter.OpschonenEINGABE(tableSet.ghMiterAprioryPercentage, tableSet, Application.getTempFile("EINGABEAJ")+(i+1)); //adjustEingabe: there was a function Adjusteingabe, but what does it do? } GHMiter.CleanGHMiterFiles(); volgNoCL = new int[maxCoverCodeList][coverDim]; for (i=0;i<TableService.numberOfTables();i++){ AdjustEingabe(i); AdjustSteuer(i); TauArgusUtils.DeleteFile(Application.getTempFile("AUSGABE")+(i+1)); } if (!Application.isAnco()){ Boolean Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("EINGABEAJ*.TMP", Application.getTempDir()); Oke = TauArgusUtils.DeleteFileWild("STEUERAJ*", Application.getTempDir()); } GHMiter.SchrijfTABELLE (Application.getTempFile("TABELLE"), 0, true, coverDim); AppendTabelle(); GHMiter.RunGHMiterEXE(); Date endDate = new Date(); long diff = endDate.getTime()-startDate.getTime(); diff = diff / 1000; if ( diff == 0){ diff = 1;} if (!TauArgusUtils.ExistFile(Application.getTempFile("AUSGABE1"))){ throw new ArgusException("GHMiter could not finish the linked protection succesfully;\n"+ "see also file: "+ Application.getTempFile("proto002")); } hs = ""; for (i=0;i<TableService.numberOfTables();i++){ tableSet=TableService.getTable(i); if (!GHMiter.ReadSecondariesGHMiter(tableSet, "AUSGABE"+(i+1))){ throw new ArgusException("Unable to read the hypercube results for table "+(i+1));} tableSet.processingTime = (int) diff; tableSet.linkSuppressed = true; hs = hs + tableSet.CountSecondaries() + " suppressions in table "+(i+1) + "\n"; } SystemUtils.writeLogbook("End of Hypercube linked tables procedure\n"+ hs + (int) diff +" seconds processing time"); return true; } static void AppendTabelle()throws ArgusException{ int i, j, k, n; TableSet tableSet; Boolean Oke; try{ BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("TABELLE"), true)); n = TableService.numberOfTables(); for(i=0;i<n;i++){ out.write("EINGABE"+(i+1)); out.newLine(); out.write("STEUER"+(i+1)); out.newLine(); out.write("AUSGABE"+(i+1)); out.newLine(); } // per table list the variables of the cover table not in this table for(i=0;i<n;i++){ tableSet = TableService.getTable(i); j = coverDim - tableSet.expVar.size(); out.write(""+j); out.newLine(); for (k=0;k<coverDim;k++){Oke = false; for (j=0;j<tableSet.expVar.size();j++){ if (coverVariablesName[k].equals(tableSet.expVar.get(j).name)) {Oke = true;} } if (!Oke){ out.write("'"+coverVariablesName[k]+"'"); out.newLine(); out.write("00000000"); out.newLine(); } } } out.close(); }catch (Exception ex){ throw new ArgusException ("An error occurred when appending the file STEUER");} } static void AdjustSteuer(int tabNo)throws ArgusException{ int i, j, nc; String hs; String regelOut; String[] regel = new String[1]; TableSet tableSet=TableService.getTable(tabNo); int nv = tableSet.expVar.size(); try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("STEUERAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("STEUER")+(tabNo+1))); for (i=0;i<6;i++){ regel[0]= in.readLine(); out.write(regel[0]); out.newLine(); } for (i=0;i<nv;i++){ regel[0]= in.readLine(); out.write("'"+tableSet.expVar.get(i).name+"'"); out.newLine(); regel[0] = in.readLine(); out.write(regel[0]); out.newLine(); j = tableSet.expVar.get(i).index; nc = TauArgusUtils.getNumberOfActiveCodes(j); while (nc>0){ regel[0]= in.readLine(); regelOut = ""; while (!regel[0].equals("")){ hs = TauArgusUtils.GetSimpleToken(regel); j = Integer.parseInt(hs); regelOut = regelOut + plusNul(volgNoCL[j][i])+" "; nc=nc-1;} out.write(regelOut); out.newLine(); } } hs = in.readLine(); while (!(hs == null)){ out.write(hs); out.newLine(); hs = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file STEUER"+(tabNo+1)+ " for linked tables");} } static void AdjustEingabe(int tabNo)throws ArgusException{ String[] regel = new String[1]; String regelOut, hs; int i, j, k, c; // replace the codes in EINGABE to correspond with the cover table TableSet tableSet=TableService.getTable(tabNo); int nc = tableSet.expVar.size(); String[] codes = new String[nc]; String[] volgno = new String[nc]; try{ BufferedReader in = new BufferedReader(new FileReader(Application.getTempFile("EINGABEAJ")+(tabNo+1))); BufferedWriter out = new BufferedWriter(new FileWriter(Application.getTempFile("EINGABE")+(tabNo+1))); regel[0] = in.readLine(); while (!(regel[0] == null)){ regel[0] = regel[0].trim(); regelOut = ""; for (i=0;i<7;i++){ hs = TauArgusUtils.GetSimpleToken(regel); regelOut = regelOut + hs + " ";} // regel[0] =<SUF> for (i=0;i<nc;i++){volgno[i] = TauArgusUtils.GetQuoteToken(regel); volgno[i] = volgno[i].replace("'", "");} for (i=0;i<nc;i++){codes[i] = TauArgusUtils.GetQuoteToken(regel); codes[i] = codes[i].replace("'", ""); codes[i] = codes[i].trim();} for (i=0;i<nc;i++){ k=toCoverIndex[tabNo][i]; c=-1; for (j=0;j<coverVarSize[k];j++){ if (codes[i].equals("")){c=0;} else{ if (codes[i].equals(coverCodelist[k][j].trim())){c=j;j=coverVarSize[k]+2;} } } if (c==-1) {throw new ArgusException("An error occurred ");} j = Integer.parseInt(volgno[i]); volgNoCL[j][i] = c; regelOut = regelOut + "'" + plusNul(c) + "' "; } for (i=0;i<nc;i++){regelOut = regelOut + "'"+codes[i]+"' ";} out.write(regelOut); out.newLine(); regel[0] = in.readLine(); } in.close(); out.close(); } catch (Exception ex){ throw new ArgusException ("An error occurred when reading and adjusting the file EINGABE"+(tabNo+1)+ " for linked tables");} } static String plusNul(int c){ String hs; int l; hs = "" + c; l = 8-hs.length(); hs = nullen.substring(0,l)+hs; return hs; } static void checkCodeList()throws ArgusException{ int i, j, k, vi, nt; TableSet tableSet; String hs, xs; Boolean found; //Make a list of all the codes in the cover table. //this will be used later for checking (modular) and futher processing in GHMiter. maxCoverCodeList = 0; nt = TableService.numberOfTables(); for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (maxCoverCodeList < k) {maxCoverCodeList = k;} } } coverCodelist = new String[coverDim][maxCoverCodeList]; for (i=0;i<coverDim;i++){ for (j=1;j<TauArgusUtils.getNumberOfActiveCodes(coverVariablesIndex[i]);j++){ coverCodelist[i][j] = TauArgusUtils.getCode(coverVariablesIndex[i], j); } coverCodelist[i][0] = Application.getVariable(coverVariablesIndex[i]).getTotalCode(); } //The actual checking for (i=0;i<nt;i++){ // all tables tableSet=TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ //all expVars vi=tableSet.expVar.get(j).index; for(k=1;k<TauArgusUtils.getNumberOfActiveCodes(vi);k++){ hs = TauArgusUtils.getCode(vi, k); int l=1; int cv = coverVariablesIndex[toCoverIndex[i][j]]; found = false; while (l<TauArgusUtils.getNumberOfActiveCodes(cv)){ xs = TauArgusUtils.getCode(cv,l); if (xs.equals(hs)){ found = true; break;} l++; } if (!found) {throw new ArgusException("code ("+hs+") not found in the cover table\n"+ "cover var "+coverVariablesName[cv]+"\n"+ "base table "+String.valueOf(i+1));} } } } } public static boolean buildCoverTable(){ TableSet tableSet; String hs; int found, i, j, k; coverVariablesName = new String[10]; coverVariablesIndex = new int[10]; coverSourceTab = new int[10]; coverVarSize = new int[10]; coverDim = 0; int n = TableService.numberOfTables(); toCoverIndex = new int [n][TableSet.MAX_RESP_VAR]; for (i=0;i<n;i++){ tableSet = TableService.getTable(i); for (j=0;j<tableSet.expVar.size();j++){ hs = tableSet.expVar.get(j).name; found = -1; for (k=0;k<coverDim;k++){ if (coverVariablesName[k].equals(hs)){found = k;} } if (found == -1) { coverDim++; coverVariablesName[coverDim-1] = hs; coverVariablesIndex[coverDim-1] = tableSet.expVar.get(j).index; coverSourceTab[coverDim-1] = i; coverVarSize[coverDim-1] = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); found = coverDim-1; } else { k = TauArgusUtils.getNumberOfActiveCodes(tableSet.expVar.get(j).index); if (coverVarSize[found]<k){ coverVarSize[found]=k; coverSourceTab[found] = i; coverVariablesIndex[found] = tableSet.expVar.get(j).index; } } toCoverIndex[i][j] = found; } } return true; } }
718_1
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet in edifact zetten } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
frankframework/frankframework
nn-specials/src/main/java/org/frankframework/extensions/afm/Afm2EdiFactSender.java
3,242
/** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */
block_comment
nl
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML<SUF>*/ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet in edifact zetten } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
718_3
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet in edifact zetten } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
frankframework/frankframework
nn-specials/src/main/java/org/frankframework/extensions/afm/Afm2EdiFactSender.java
3,242
//TODO: checken of dit wel klopt, stond zo in originele EvdW-code
line_comment
nl
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken<SUF> if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet in edifact zetten } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
718_5
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet in edifact zetten } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
frankframework/frankframework
nn-specials/src/main/java/org/frankframework/extensions/afm/Afm2EdiFactSender.java
3,242
//Verwerktags niet in edifact zetten
line_comment
nl
/* Copyright 2013 Nationale-Nederlanden, 2020, 2022-2023 WeAreFrank! 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.frankframework.extensions.afm; import java.text.DecimalFormat; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lombok.Getter; import lombok.Setter; import org.frankframework.core.ISender; import org.frankframework.core.PipeLineSession; import org.frankframework.core.SenderException; import org.frankframework.core.SenderResult; import org.frankframework.doc.Category; import org.frankframework.stream.Message; import org.frankframework.util.DateFormatUtils; import org.frankframework.util.DomBuilderException; import org.frankframework.util.LogUtil; import org.frankframework.util.XmlUtils; /** * Domparser om AFM-XML berichten om te zetten in edifactberichten (voor de backoffice). * * @author Erik van de Wetering, fine tuned and wrapped for Ibis by Gerrit van Brakel */ @Category("NN-Special") public class Afm2EdiFactSender implements ISender { protected Logger logger = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private @Getter @Setter ApplicationContext applicationContext; public static final String VERWERKTAG = "VRWRKCD"; public static final String TPNRTAG = "AL_RECCRT"; private static final String contractRoot = "Contractdocument"; private static final String mantelRoot = "Mantel"; private static final String onderdeelRoot = "Onderdeel"; private String destination = " "; // 3 tekens private String tpnummer = "999999"; // 6 tekens indien label AL_RECCRT ontbreekt private String postbus = " "; //16 tekens private String name; @Override public void configure() { } @Override public void open() { } @Override public void close() { } @Override public boolean isSynchronous() { return true; } @Override public SenderResult sendMessage(Message message, PipeLineSession session) throws SenderException { try { return new SenderResult(execute(message.asString())); } catch (Exception e) { throw new SenderException("transforming AFM-XML to EdiFact",e); } } private void appendArray(char[] aArray, StringBuilder aRes) { String aStr = new String(aArray); appendString(aStr, aRes); } private void appendString(String aStr, StringBuilder aRes) { if (aStr != null) { String lHlpStr = aStr.trim(); //TODO: checken of dit wel klopt, stond zo in originele EvdW-code if (aStr.length() > 1) { aRes.append(aStr.intern() + "\r\n"); } } } private boolean bevatWaarde(Node aNode) { String lWaarde = getWaardeForNode(aNode); boolean lRes = false; if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; } if (!lRes) { NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); lWaarde = getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lRes = true; break; } else { boolean lHlpRes = bevatWaarde(aSubNode); if (lHlpRes) { lRes = lHlpRes; break; } } } } return lRes; } private void closeList(StringBuilder aRes, int regelTeller) { // UNT char untRegel[] = new char[21]; for (int i = 0; i < 21; i++) untRegel[i] = ' '; "UNT".getChars(0, "UNT".length(), untRegel, 0); DecimalFormat df = new DecimalFormat("000000"); regelTeller++; //de UNT Regel zelf df.format(regelTeller).getChars(0,df.format(regelTeller).length(),untRegel,3); appendArray(untRegel, aRes); regelTeller = 0; } public String execute(String aInput) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(aInput); NodeList contractList = doc.getElementsByTagName(contractRoot); NodeList mantelList = doc.getElementsByTagName(mantelRoot); NodeList onderdeelList = doc.getElementsByTagName(onderdeelRoot); NodeList tpNr = doc.getElementsByTagName(TPNRTAG); if (tpNr.getLength() > 0) { Node lHlpNode = tpNr.item(0); setTpnummer(getWaardeForNode(lHlpNode)); } StringBuilder resultaat = new StringBuilder(); //start this.appendArray(getInitResultaat(), resultaat); //docs this.HandleList(contractList, resultaat); this.HandleList(mantelList, resultaat); this.HandleList(onderdeelList, resultaat); //finish this.appendArray(getCloseResultaat(), resultaat); return resultaat.toString(); } public char[] getCloseResultaat() { // UNZ char unzRegel[] = new char[23]; for (int i = 0; i < 23; i++) unzRegel[i] = ' '; "UNZ000001".getChars(0, "UNZ000001".length(), unzRegel, 0); return unzRegel; } public char[] getInitResultaat() { // UNB char unbRegel[] = new char[206]; for (int i = 0; i < 206; i++) unbRegel[i] = ' '; String lStart = "UNBUNOC1INFONET " + getDestination() + " TP"; lStart.getChars(0, lStart.length(), unbRegel, 0); getTpnummer().getChars(0, getTpnummer().length(), unbRegel, 26); String lPostbus = getPostbus(); lPostbus.getChars(0, lPostbus.length(), unbRegel, 61); String dateTime = DateFormatUtils.now("yyMMddHHmm"); dateTime.getChars(0, dateTime.length(), unbRegel, 114); "0".getChars(0, "0".length(), unbRegel, 169); "0".getChars(0, "0".length(), unbRegel, 205); return unbRegel; } private String getLabelNaam(String aLabel) { String lRes = aLabel; if (lRes != null) { if (lRes.startsWith("Q")) { lRes = "#" + lRes.substring(1); } } return lRes; } private char[] getNewDocInit() { char unhRegel[] = new char[74]; for (int i = 0; i < 74; i++) unhRegel[i] = ' '; "UNH".getChars(0, "UNH".length(), unhRegel, 0); "INSLBW001000IN".getChars(0, "INSLBW001000IN".length(), unhRegel, 17); "00".getChars(0, "00".length(), unhRegel, 72); return unhRegel; } private String getVerwerkCdNaamForNode(Node aNode) { String lRes = aNode.getNodeName() + "_" + VERWERKTAG; return lRes; } private String getVerwerkCdWaarde(Node aNode) { NodeList aList = aNode.getChildNodes(); String lRes = ""; String verwerkCdNaam = this.getVerwerkCdNaamForNode(aNode); for (int i = 0; i <= aList.getLength() - 1; i++) { Node aChild = aList.item(i); if (verwerkCdNaam.equalsIgnoreCase(aChild.getNodeName())) { lRes = getWaardeForNode(aChild); break; } } return lRes; } private String getWaardeForNode(Node aNode) { String lRes = ""; NodeList lList = aNode.getChildNodes(); for (int i = 0; i <= lList.getLength() - 1; i++) { Node aSubNode = lList.item(i); if ((aSubNode.getNodeType() == Node.TEXT_NODE) || (aSubNode.getNodeType() == Node.CDATA_SECTION_NODE)) { lRes = lRes + aSubNode.getNodeValue(); } } return lRes; } private StringBuilder HandleList(NodeList aList, StringBuilder aRes) { if (aList != null) { if (aList.getLength() > 0) { for (int i = 0; i <= aList.getLength() - 1; i++) { int regelTeller = 1; this.appendArray(getNewDocInit(), aRes); Node aNode = aList.item(i); NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); closeList(aRes,regelTeller); } } } return aRes; } private int HandleSubList(NodeList aList, StringBuilder aRes, int regelTeller) { String lHlp = ""; if (aList != null) { for (int i = 0; i <= aList.getLength() - 1; i++) { Node aNode = aList.item(i); if (aNode.getNodeType() == Node.ELEMENT_NODE) { if (bevatWaarde(aNode)) { String labelNaam = this.getLabelNaam(aNode.getNodeName()); if (labelNaam.length() == 2) { // Entiteit gevonden lHlp = "ENT" + labelNaam + getVerwerkCdWaarde(aNode); appendString(lHlp, aRes); regelTeller++; NodeList aSubList = aNode.getChildNodes(); regelTeller = HandleSubList(aSubList, aRes, regelTeller); } else { if (labelNaam.contains(VERWERKTAG)) { //Verwerktags niet<SUF> } else { lHlp = "LBW" + labelNaam.substring(3); // Spaties toevoegen for (int lTel = lHlp.length(); lTel < 10; lTel++) { lHlp += " "; } String lWaarde = this.getWaardeForNode(aNode); if ((lWaarde != null) && (!"".equalsIgnoreCase(lWaarde))) { lHlp = lHlp + lWaarde; this.appendString(lHlp, aRes); regelTeller++; } } } } } } } return regelTeller; } @Override public void setName(String name) { this.name=name; } @Override public String getName() { return name; } public void setDestination(String newDestination) { destination = newDestination; } public String getDestination() { return destination; } public void setPostbus(String newPostbus) { postbus = newPostbus; } public String getPostbus() { return postbus; } public void setTpnummer(String newTpnummer) { logger.info("Tpnr: " + newTpnummer); tpnummer = newTpnummer; } public String getTpnummer() { return tpnummer; } }
722_12
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import java.io.IOException; import jd.PluginWrapper; import jd.nutils.encoding.Encoding; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import org.jdownloader.downloader.hls.HLSDownloader; import org.jdownloader.plugins.components.hls.HlsContainer; /* * vrt.be network * old content handling --> var vars12345 = Array(); */ @HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://cobradecrypted\\.be/\\d+" }) public class CobraBe extends PluginForHost { public CobraBe(PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://cobra.canvas.be/"; } // JSARRAY removed after rev 20337 @Override public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException { this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(downloadLink.getStringProperty("mainlink", null)); // Link offline if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || !br.containsHTML("class=\"media flashPlayer bigMediaItem\"") || this.br.getHttpConnection().getResponseCode() == 404) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0); if (filename == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String ext = ".mp4"; downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "") + ext); return AvailableStatus.TRUE; } @Override public void handleFree(final DownloadLink downloadLink) throws Exception { requestFileInformation(downloadLink); final String hlsserver = br.getRegex("data-video-iphone-server=\"(https?://[^<>\"]*?)\"").getMatch(0); final String hlsfile = br.getRegex("data-video-iphone-path=\"(mp4:[^<>\"]*?\\.m3u8)\"").getMatch(0); if (hlsserver == null || hlsfile == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String hlsmanifest = hlsserver + "/" + hlsfile; br.getPage(hlsmanifest); final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br)); if (hlsbest == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String url_hls = hlsbest.getDownloadurl(); checkFFmpeg(downloadLink, "Download a HLS Stream"); dl = new HLSDownloader(downloadLink, br, url_hls); dl.startDownload(); } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void reset() { } @Override public void resetPluginGlobals() { } @Override public void resetDownloadlink(DownloadLink link) { } }
substanc3-dev/jdownloader2
src/jd/plugins/hoster/CobraBe.java
1,123
/* * vrt.be network * old content handling --> var vars12345 = Array(); */
block_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import java.io.IOException; import jd.PluginWrapper; import jd.nutils.encoding.Encoding; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import org.jdownloader.downloader.hls.HLSDownloader; import org.jdownloader.plugins.components.hls.HlsContainer; /* * vrt.be network <SUF>*/ @HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://cobradecrypted\\.be/\\d+" }) public class CobraBe extends PluginForHost { public CobraBe(PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://cobra.canvas.be/"; } // JSARRAY removed after rev 20337 @Override public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException { this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(downloadLink.getStringProperty("mainlink", null)); // Link offline if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || !br.containsHTML("class=\"media flashPlayer bigMediaItem\"") || this.br.getHttpConnection().getResponseCode() == 404) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0); if (filename == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String ext = ".mp4"; downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "") + ext); return AvailableStatus.TRUE; } @Override public void handleFree(final DownloadLink downloadLink) throws Exception { requestFileInformation(downloadLink); final String hlsserver = br.getRegex("data-video-iphone-server=\"(https?://[^<>\"]*?)\"").getMatch(0); final String hlsfile = br.getRegex("data-video-iphone-path=\"(mp4:[^<>\"]*?\\.m3u8)\"").getMatch(0); if (hlsserver == null || hlsfile == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String hlsmanifest = hlsserver + "/" + hlsfile; br.getPage(hlsmanifest); final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br)); if (hlsbest == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String url_hls = hlsbest.getDownloadurl(); checkFFmpeg(downloadLink, "Download a HLS Stream"); dl = new HLSDownloader(downloadLink, br, url_hls); dl.startDownload(); } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void reset() { } @Override public void resetPluginGlobals() { } @Override public void resetDownloadlink(DownloadLink link) { } }
724_3
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//twitter.com/Tillerinobot voor status en updates!"
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor<SUF> + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
724_5
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
724_8
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel]<SUF> "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
724_9
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn<SUF> "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
724_10
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank<SUF> "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
724_11
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Tillerino/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,410
//gabrielecirulli.github.io/2048/ 2048] eens een keer!",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.ppaddict.chat.GameChatResponse; import org.tillerino.ppaddict.chat.GameChatResponse.Action; import org.tillerino.ppaddict.chat.GameChatResponse.Message; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; String message = messages[ThreadLocalRandom.current().nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public GameChatResponse hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current()); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048]<SUF> "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
730_0
package entity; public class Game extends Media{ private String uitgever; public Game(String titel, String beschrijving, double rating, String uitgever) { super(titel, beschrijving, rating); this.uitgever = uitgever; } public Game(int id, String titel, String beschrijving, double rating, String uitgever) { super(id, titel, beschrijving, rating); this.uitgever = uitgever; } @Override public void verplaatsNaarArchief() { //doet er niet toe } public String getUitgever() { return uitgever; } }
EHB-TI/Programming-Essentials-2
Werkcollege10/src/entity/Game.java
159
//doet er niet toe
line_comment
nl
package entity; public class Game extends Media{ private String uitgever; public Game(String titel, String beschrijving, double rating, String uitgever) { super(titel, beschrijving, rating); this.uitgever = uitgever; } public Game(int id, String titel, String beschrijving, double rating, String uitgever) { super(id, titel, beschrijving, rating); this.uitgever = uitgever; } @Override public void verplaatsNaarArchief() { //doet er<SUF> } public String getUitgever() { return uitgever; } }
733_12
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.HashMap; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporza\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" }) public class DeredactieBe extends PluginForDecrypt { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(parameter); // Link offline if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src"); if (finalurl == null) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } return decryptedLinks; } if (finalurl.contains("youtube.com")) { decryptedLinks.add(createDownloadlink(finalurl)); } else { decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/"))); } return decryptedLinks; } /* NO OVERRIDE!! */ public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) { return false; } }
substanc3-dev/jdownloader2
src/jd/plugins/decrypter/DeredactieBe.java
896
//(www\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporza\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" })
line_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.HashMap; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporza\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)"<SUF> public class DeredactieBe extends PluginForDecrypt { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(parameter); // Link offline if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src"); if (finalurl == null) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } return decryptedLinks; } if (finalurl.contains("youtube.com")) { decryptedLinks.add(createDownloadlink(finalurl)); } else { decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/"))); } return decryptedLinks; } /* NO OVERRIDE!! */ public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) { return false; } }
737_12
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.Random; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.nutils.encoding.Encoding; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://(www\\.)?cobra(?:\\.canvas)?\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|cobra)([^/]+)?/(mediatheek|videozone).+)" }) public class CobraBeDecrypter extends PluginForDecrypt { public CobraBeDecrypter(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); parameter = parameter.replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1"); parameter = parameter.replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3"); final DownloadLink mainlink = createDownloadlink("http://cobradecrypted.be/" + System.currentTimeMillis() + new Random().nextInt(1000000)); this.br.setFollowRedirects(true); br.getPage(parameter); mainlink.setProperty("mainlink", this.br.getURL()); final String externID = br.getRegex("data\\-video\\-src=\"(https?://(www\\.)?youtube\\.com/[^<>\"]*?)\"").getMatch(0); if (externID != null) { decryptedLinks.add(createDownloadlink(externID)); return decryptedLinks; } if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || this.br.getHttpConnection().getResponseCode() == 404) { final DownloadLink offline = this.createOfflinelink(parameter); decryptedLinks.add(offline); return decryptedLinks; } final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0); if (filename != null) { mainlink.setLinkID(filename); mainlink.setName(Encoding.htmlDecode(filename.trim())); } decryptedLinks.add(mainlink); return decryptedLinks; } }
substanc3-dev/jdownloader2
src/jd/plugins/decrypter/CobraBeDecrypter.java
880
//(www\\.)?cobra(?:\\.canvas)?\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|cobra)([^/]+)?/(mediatheek|videozone).+)" })
line_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.Random; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.nutils.encoding.Encoding; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "cobra.be" }, urls = { "http://(www\\.)?cobra(?:\\.canvas)?\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|cobra)([^/]+)?/(mediatheek|videozone).+)" })<SUF> public class CobraBeDecrypter extends PluginForDecrypt { public CobraBeDecrypter(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); parameter = parameter.replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1"); parameter = parameter.replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3"); final DownloadLink mainlink = createDownloadlink("http://cobradecrypted.be/" + System.currentTimeMillis() + new Random().nextInt(1000000)); this.br.setFollowRedirects(true); br.getPage(parameter); mainlink.setProperty("mainlink", this.br.getURL()); final String externID = br.getRegex("data\\-video\\-src=\"(https?://(www\\.)?youtube\\.com/[^<>\"]*?)\"").getMatch(0); if (externID != null) { decryptedLinks.add(createDownloadlink(externID)); return decryptedLinks; } if (br.containsHTML(">Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden") || this.br.getHttpConnection().getResponseCode() == 404) { final DownloadLink offline = this.createOfflinelink(parameter); decryptedLinks.add(offline); return decryptedLinks; } final String filename = br.getRegex("data\\-video\\-title=\"([^<>\"]*?)\"").getMatch(0); if (filename != null) { mainlink.setLinkID(filename); mainlink.setName(Encoding.htmlDecode(filename.trim())); } decryptedLinks.add(mainlink); return decryptedLinks; } }
740_31
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone); if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
aunroel/the-one
src/routing/ProphetRouterWithEstimation.java
4,543
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
line_comment
nl
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t<SUF> if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
742_21
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
PacktPublishing/Build-Your-Own-Programming-Language
ch4/Parser.java
4,494
// methods: state stack push,pop,drop,peek
line_comment
nl
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state<SUF> //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
742_29
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
PacktPublishing/Build-Your-Own-Programming-Language
ch4/Parser.java
4,494
// methods: value stack push,pop,drop,peek.
line_comment
nl
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value<SUF> //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
742_46
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
PacktPublishing/Build-Your-Own-Programming-Language
ch4/Parser.java
4,494
//it it didn't work/error
line_comment
nl
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it<SUF> { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
742_83
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
PacktPublishing/Build-Your-Own-Programming-Language
ch4/Parser.java
4,494
//get next character
line_comment
nl
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next<SUF> if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
742_90
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
PacktPublishing/Build-Your-Own-Programming-Language
ch4/Parser.java
4,494
//get new state
line_comment
nl
//### This file created by BYACC 1.8(/Java extension 1.15) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### 06 Aug 00 -- Bob Jamison -- made state variables class-global //### 03 Jan 01 -- Bob Jamison -- improved flags, tracing //### 16 May 01 -- Bob Jamison -- added custom stack sizing //### 04 Mar 02 -- Yuval Oren -- improved java performance, added options //### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround //### Please send bug reports to [email protected] //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; package ch4; import static ch4.lexer.yylex; import static ch4.yyerror.yyerror; public class Parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[] = new int[YYSTACKSIZE]; //state stack int stateptr; int stateptrmax; //highest index of stackptr int statemax; //state when highest index reached //############################################################### // methods: state stack push,pop,drop,peek //############################################################### final void state_push(int state) { try { stateptr++; statestk[stateptr]=state; } catch (ArrayIndexOutOfBoundsException e) { int oldsize = statestk.length; int newsize = oldsize * 2; int[] newstack = new int[newsize]; System.arraycopy(statestk,0,newstack,0,oldsize); statestk = newstack; statestk[stateptr]=state; } } final int state_pop() { return statestk[stateptr--]; } final void state_drop(int cnt) { stateptr -= cnt; } final int state_peek(int relative) { return statestk[stateptr-relative]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### final boolean init_stacks() { stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i<count;i++) System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]); System.out.println("======================"); } //########## SEMANTIC VALUES ########## //public class ParserVal is defined in ParserVal.java String yytext;//user variable to return contextual strings ParserVal yyval; //used to return semantic vals from action routines ParserVal yylval;//the 'lval' (result) I got from yylex() ParserVal valstk[]; int valptr; //############################################################### // methods: value stack push,pop,drop,peek. //############################################################### void val_init() { valstk=new ParserVal[YYSTACKSIZE]; yyval=new ParserVal(); yylval=new ParserVal(); valptr=-1; } void val_push(ParserVal val) { if (valptr>=YYSTACKSIZE) return; valstk[++valptr]=val; } ParserVal val_pop() { if (valptr<0) return new ParserVal(); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } ParserVal val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new ParserVal(); return valstk[ptr]; } final ParserVal dup_yyval(ParserVal val) { ParserVal dup = new ParserVal(); dup.ival = val.ival; dup.dval = val.dval; dup.sval = val.sval; dup.obj = val.obj; return dup; } //#### end semantic value section #### public final static short NAME=257; public final static short NUMBER=258; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 0, 1, }; final static short yylen[] = { 2, 2, 0, 2, }; final static short yydefred[] = { 0, 0, 0, 0, 3, 1, }; final static short yydgoto[] = { 2, 3, }; final static short yysindex[] = { -257, -256, 0, -257, 0, 0, }; final static short yyrindex[] = { 1, 0, 0, 1, 0, 0, }; final static short yygindex[] = { 2, 0, }; final static int YYTABLESIZE=5; static short yytable[]; static { yytable();} static void yytable(){ yytable = new short[]{ 1, 2, 4, 0, 0, 5, }; } static short yycheck[]; static { yycheck(); } static void yycheck() { yycheck = new short[] { 257, 0, 258, -1, -1, 3, }; } final static short YYFINAL=2; final static short YYMAXTOKEN=258; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,"NAME","NUMBER", }; final static String yyrule[] = { "$accept : sequence", "sequence : pair sequence", "sequence :", "pair : NAME NUMBER", }; //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //The following are now global, to aid in error reporting int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it val_push(yylval); //save empty value while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token if (yydebug) debug(" next yychar:"+yychar); //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new<SUF> else yystate = yydgoto[yym]; //else go to new defred if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### //## run() --- for Thread ####################################### /** * A default run method, used for operating this parser * object in the background. It is intended for extending Thread * or implementing Runnable. Turn off with -Jnorun . */ public void run() { yyparse(); } //## end of method run() ######################################## //## Constructors ############################################### /** * Default constructor. Turn off with -Jnoconstruct . */ public Parser() { //nothing to do } /** * Create a parser, setting the debug to true or false. * @param debugMe true for debugging, false for no debug. */ public Parser(boolean debugMe) { yydebug=debugMe; } //############################################################### } //################### END OF CLASS ##############################
743_4
/* * 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.jena.iri.impl; import java.io.UnsupportedEncodingException; import java.util.AbstractSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.apache.jena.iri.IRI ; import org.apache.jena.iri.IRIComponents ; import org.apache.jena.iri.ViolationCodes ; public class IRIFactoryImpl extends AbsIRIFactoryImpl implements ViolationCodes, Force, IRIComponents { public static final int UNKNOWN_SYNTAX = -4; // boolean throwUncheckedExceptions = false; /* static final long conformanceMasks[] = { // RFC3986 (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<IRI_CHAR) |(1l<<LTR_CHAR) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<UNWISE_CHAR) |(1l<<WHITESPACE) |(1l<<ARBITRARY_CHAR) , // RFC3987 (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<LTR_CHAR) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<UNWISE_CHAR) |(1l<<WHITESPACE) |(1l<<ARBITRARY_CHAR) , // RDF (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<RELATIVE_URI) , // XLink (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<NON_XML_CHARACTER) , // XMLSchema (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<NON_XML_CHARACTER) , // IDN // (1l<<ACE_PREFIX) 0 , // Should (1l<<LOWERCASE_PREFERRED) |(1l<<PORT_SHOULD_NOT_BE_EMPTY) |(1l<<PORT_SHOULD_NOT_START_IN_ZERO) // |(1l<<SCHEME_NAMES_SHOULD_BE_LOWER_CASE) |(1l<<PERCENT_ENCODING_SHOULD_BE_UPPERCASE) |(1l<<IPv6ADDRESS_SHOULD_BE_LOWERCASE) |(1l<<USE_PUNYCODE_NOT_PERCENTS) , // Minting /* consider HAS_PASSWORD vs LOWER_CASE_PREFERRED * The former should be an error unless switched * off (but it can be, unlike a MUST), whereas the * latter should be a warning by default. * / (1l<<LOWERCASE_PREFERRED) |(1l<<PORT_SHOULD_NOT_BE_EMPTY) |(1l<<PORT_SHOULD_NOT_START_IN_ZERO) // |(1l<<SCHEME_NAMES_SHOULD_BE_LOWER_CASE) |(1l<<PERCENT_ENCODING_SHOULD_BE_UPPERCASE) |(1l<<IPv6ADDRESS_SHOULD_BE_LOWERCASE) |(1l<<USE_PUNYCODE_NOT_PERCENTS) , // DNS (1l<<NOT_DNS_NAME) , }; */ protected long errors; protected long warnings; protected Set<Specification> specs = new HashSet<>(); public IRIFactoryImpl() { } public IRIFactoryImpl(IRIFactoryImpl template) { if (backwardCompatibleRelativeRefs.size()==Integer.MAX_VALUE) backwardCompatibleRelativeRefs = template.backwardCompatibleRelativeRefs; else backwardCompatibleRelativeRefs = new HashSet<>(backwardCompatibleRelativeRefs); encoding = template.encoding; errors = template.errors; prohibited = template.prohibited; required = template.required; warnings = template.warnings; System.arraycopy(template.asErrors,0,asErrors,0,asErrors.length); System.arraycopy(template.asWarnings,0,asWarnings,0,asWarnings.length); for ( Entry<String, SchemeSpecificPart> entry : template.schemes.entrySet() ) { SchemeSpecificPart p = entry.getValue(); if ( p.withScheme() ) { schemes.put( entry.getKey(), new WithScheme( (WithScheme) p ) ); } else if ( p.port() != IRI.NO_PORT ) { schemes.put( entry.getKey(), new NoScheme( p.port() ) ); } } } /* protected long recsToMask(int recs) { long mask = 0; for (int i=0; recs != 0 && i<conformanceMasks.length; i++) { if ((recs & (1<<i)) != 0) { mask |= conformanceMasks[i]; recs &= ~(1<<i); } } return mask; } */ private final long getMask(boolean includeWarnings) { return includeWarnings?(errors|warnings):errors; } @Override protected IRIFactoryImpl getFactory() { return this; } @Override public IRI create(IRI i) { if (i instanceof AbsIRIImpl && ((AbsIRIImpl)i).getFactory()==this) return i; return create(i.toString()); } boolean getSameSchemaRelativeReferences(String scheme) { return backwardCompatibleRelativeRefs.contains(scheme.toLowerCase()); } private String encoding = "utf-8"; String getEncoding() { return encoding; } public void setEncoding(String enc) throws UnsupportedEncodingException { // check enc is valid encoding. "".getBytes(enc); encoding = enc; } boolean asErrors[] = new boolean[]{ true, true, false, true, true, true, }; boolean asWarnings[] = new boolean[]{ false, false, true, false, false, false }; protected void setViolation(int ix, boolean e, boolean w){ if (e && w) throw new IllegalArgumentException("xxxViolation(true,true) is not permitted."); initializing(); asErrors[ix]=e; asWarnings[ix]=w; } protected boolean getAsWarnings(int ix) { return asWarnings[ix]; } protected boolean getAsErrors(int ix) { return asErrors[ix]; } // boolean isException(int code) { // return (errors & (1l<<code))!=0; // } private boolean initializing = true; private Set<String> backwardCompatibleRelativeRefs = new HashSet<>(); protected void initializing() { if (!initializing) throw new IllegalStateException("Cannot reinitialize IRIFactory after first use."); } @Override public IRI create(String s) { initializing = false; return super.create(s); } public void setSameSchemeRelativeReferences(String scheme) { if (scheme.equals("*")) backwardCompatibleRelativeRefs = new AbstractSet<String>(){ @Override public int size() { return Integer.MAX_VALUE; } @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } @Override public boolean add(String o) { return false; } @Override public boolean contains(Object o) { return true; } }; else backwardCompatibleRelativeRefs.add(scheme.toLowerCase()); } protected void useSpec(String name, boolean asErr) { initializing(); Specification spec = Specification.get(name); specs.add(spec); for (int i=0; i<Force.SIZE; i++) { if (asErrors[i] || (asWarnings[i] && asErr)) { errors |= spec.getErrors(i); } if (asWarnings[i] ) { warnings |= spec.getErrors(i); } } prohibited |= spec.getProhibited(); required |= spec.getRequired(); warnings &= ~errors; } public SchemeSpecificPart getScheme(String scheme, Parser parser) { scheme = scheme.toLowerCase(); SchemeSpecificPart p = schemes.get(scheme); if (p!=null) { p.usedBy(parser); return p; } int dash = scheme.indexOf('-'); if (dash != -1) { if (scheme.startsWith("x-")) { p = noScheme(); } else { if (nonIETFScheme==null) nonIETFScheme = new NoScheme() { @Override void usedBy(Parser pp) { pp.recordError(SCHEME,UNREGISTERED_NONIETF_SCHEME_TREE); } }; p = nonIETFScheme; } } else if (Specification.schemes.containsKey(scheme)) { SchemeSpecification spec = (SchemeSpecification)Specification.schemes.get(scheme); p = new NoScheme(spec.port); } else{ if (unregisteredScheme==null){ unregisteredScheme = new NoScheme() { @Override void usedBy(Parser pp) { pp.recordError(SCHEME,UNREGISTERED_IANA_SCHEME); } }; } p= unregisteredScheme; } p.usedBy(parser); // System.err.println("Scheme: "+scheme); if (schemes.size() < 1000) schemes.put(scheme,p); return p; } private NoScheme unregisteredScheme=null; private NoScheme nonIETFScheme=null; public SchemeSpecificPart noScheme() { return noScheme; } private class WithScheme extends SchemeSpecificPart { long zerrors; long zwarnings; int zrequired; int zprohibited; boolean inited = false; final SchemeSpecification scheme; private WithScheme(WithScheme ws) { zerrors = ws.zerrors; zwarnings = ws.zwarnings; zprohibited = ws.zprohibited; zrequired = ws.zrequired; scheme = ws.scheme; } private WithScheme(SchemeSpecification spec, boolean asErr){ scheme = spec; for (int i=0; i<Force.SIZE; i++) { if (asErrors[i] || (asWarnings[i] && asErr)) { zerrors |= spec.getErrors(i); } if (asWarnings[i] ) { zwarnings |= spec.getErrors(i); } } } @Override void usedBy(Parser parser) { if (!inited) { inited = true; zerrors |= errors; zwarnings |= warnings; zwarnings &= ~zerrors; zrequired = scheme.getRequired() | required; zprohibited = scheme.getProhibited() | prohibited; } } @Override public long getMask(boolean includeWarnings) { return includeWarnings?(zerrors|zwarnings):zerrors; } @Override public int getRequired() { return zrequired; } @Override public int getProhibited() { return zprohibited; } @Override public void analyse(Parser parser, int range) { scheme.analyse(parser,range); } @Override public int port() { return scheme.port; } @Override public boolean withScheme() { return true; } } private class NoScheme extends SchemeSpecificPart { NoScheme() { this(-1); } final private int port; NoScheme(int i) { port = i; } @Override public long getMask(boolean includeWarnings) { return IRIFactoryImpl.this.getMask(includeWarnings); } @Override public int getRequired() { return IRIFactoryImpl.this.getRequired(); } @Override public int getProhibited() { return IRIFactoryImpl.this.getProhibited(); } @Override void usedBy(Parser parser) { /* nothing */ } @Override public void analyse(Parser parser, int range) {/* nothing */ } @Override public int port() { return port; } @Override public boolean withScheme() { return false; } } final private NoScheme noScheme = new NoScheme(); private int required = 0; private int prohibited = 0; public int getRequired() { return required; } public int getProhibited() { return prohibited ; } final private Map<String, SchemeSpecificPart> schemes = new HashMap<>(); public void useSchemeSpecificRules(String scheme, boolean asErr) { if (scheme.equals("*")) { for ( String s : Specification.schemes.keySet() ) { scheme = s; if ( !schemes.containsKey( scheme ) ) { useSchemeSpecificRules( scheme, asErr ); } } return ; } scheme = scheme.toLowerCase() ; SchemeSpecification spec = (SchemeSpecification) Specification.schemes.get(scheme) ; if (spec == null) { schemes.put(scheme, noScheme) ; } else { schemes.put(scheme, new WithScheme(spec, asErr)) ; } } }
apache/jena
jena-iri/src/main/java/org/apache/jena/iri/impl/IRIFactoryImpl.java
4,119
// check enc is valid encoding.
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.jena.iri.impl; import java.io.UnsupportedEncodingException; import java.util.AbstractSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.apache.jena.iri.IRI ; import org.apache.jena.iri.IRIComponents ; import org.apache.jena.iri.ViolationCodes ; public class IRIFactoryImpl extends AbsIRIFactoryImpl implements ViolationCodes, Force, IRIComponents { public static final int UNKNOWN_SYNTAX = -4; // boolean throwUncheckedExceptions = false; /* static final long conformanceMasks[] = { // RFC3986 (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<IRI_CHAR) |(1l<<LTR_CHAR) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<UNWISE_CHAR) |(1l<<WHITESPACE) |(1l<<ARBITRARY_CHAR) , // RFC3987 (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<LTR_CHAR) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<UNWISE_CHAR) |(1l<<WHITESPACE) |(1l<<ARBITRARY_CHAR) , // RDF (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<RELATIVE_URI) , // XLink (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<NON_XML_CHARACTER) , // XMLSchema (1l<<ILLEGAL_CHAR) |(1l<<ILLEGAL_PERCENT_ENCODING) |(1l<<EMPTY_SCHEME) |(1l<<IP_V4_HAS_FOUR_COMPONENTS) |(1l<<IP_V4_OCTET_RANGE) |(1l<<IP_V6_OR_FUTURE_ADDRESS_SYNTAX) |(1l<<SCHEME_MUST_START_WITH_LETTER) |(1l<<NOT_XML_SCHEMA_WHITESPACE) |(1l<<NON_XML_CHARACTER) , // IDN // (1l<<ACE_PREFIX) 0 , // Should (1l<<LOWERCASE_PREFERRED) |(1l<<PORT_SHOULD_NOT_BE_EMPTY) |(1l<<PORT_SHOULD_NOT_START_IN_ZERO) // |(1l<<SCHEME_NAMES_SHOULD_BE_LOWER_CASE) |(1l<<PERCENT_ENCODING_SHOULD_BE_UPPERCASE) |(1l<<IPv6ADDRESS_SHOULD_BE_LOWERCASE) |(1l<<USE_PUNYCODE_NOT_PERCENTS) , // Minting /* consider HAS_PASSWORD vs LOWER_CASE_PREFERRED * The former should be an error unless switched * off (but it can be, unlike a MUST), whereas the * latter should be a warning by default. * / (1l<<LOWERCASE_PREFERRED) |(1l<<PORT_SHOULD_NOT_BE_EMPTY) |(1l<<PORT_SHOULD_NOT_START_IN_ZERO) // |(1l<<SCHEME_NAMES_SHOULD_BE_LOWER_CASE) |(1l<<PERCENT_ENCODING_SHOULD_BE_UPPERCASE) |(1l<<IPv6ADDRESS_SHOULD_BE_LOWERCASE) |(1l<<USE_PUNYCODE_NOT_PERCENTS) , // DNS (1l<<NOT_DNS_NAME) , }; */ protected long errors; protected long warnings; protected Set<Specification> specs = new HashSet<>(); public IRIFactoryImpl() { } public IRIFactoryImpl(IRIFactoryImpl template) { if (backwardCompatibleRelativeRefs.size()==Integer.MAX_VALUE) backwardCompatibleRelativeRefs = template.backwardCompatibleRelativeRefs; else backwardCompatibleRelativeRefs = new HashSet<>(backwardCompatibleRelativeRefs); encoding = template.encoding; errors = template.errors; prohibited = template.prohibited; required = template.required; warnings = template.warnings; System.arraycopy(template.asErrors,0,asErrors,0,asErrors.length); System.arraycopy(template.asWarnings,0,asWarnings,0,asWarnings.length); for ( Entry<String, SchemeSpecificPart> entry : template.schemes.entrySet() ) { SchemeSpecificPart p = entry.getValue(); if ( p.withScheme() ) { schemes.put( entry.getKey(), new WithScheme( (WithScheme) p ) ); } else if ( p.port() != IRI.NO_PORT ) { schemes.put( entry.getKey(), new NoScheme( p.port() ) ); } } } /* protected long recsToMask(int recs) { long mask = 0; for (int i=0; recs != 0 && i<conformanceMasks.length; i++) { if ((recs & (1<<i)) != 0) { mask |= conformanceMasks[i]; recs &= ~(1<<i); } } return mask; } */ private final long getMask(boolean includeWarnings) { return includeWarnings?(errors|warnings):errors; } @Override protected IRIFactoryImpl getFactory() { return this; } @Override public IRI create(IRI i) { if (i instanceof AbsIRIImpl && ((AbsIRIImpl)i).getFactory()==this) return i; return create(i.toString()); } boolean getSameSchemaRelativeReferences(String scheme) { return backwardCompatibleRelativeRefs.contains(scheme.toLowerCase()); } private String encoding = "utf-8"; String getEncoding() { return encoding; } public void setEncoding(String enc) throws UnsupportedEncodingException { // check enc<SUF> "".getBytes(enc); encoding = enc; } boolean asErrors[] = new boolean[]{ true, true, false, true, true, true, }; boolean asWarnings[] = new boolean[]{ false, false, true, false, false, false }; protected void setViolation(int ix, boolean e, boolean w){ if (e && w) throw new IllegalArgumentException("xxxViolation(true,true) is not permitted."); initializing(); asErrors[ix]=e; asWarnings[ix]=w; } protected boolean getAsWarnings(int ix) { return asWarnings[ix]; } protected boolean getAsErrors(int ix) { return asErrors[ix]; } // boolean isException(int code) { // return (errors & (1l<<code))!=0; // } private boolean initializing = true; private Set<String> backwardCompatibleRelativeRefs = new HashSet<>(); protected void initializing() { if (!initializing) throw new IllegalStateException("Cannot reinitialize IRIFactory after first use."); } @Override public IRI create(String s) { initializing = false; return super.create(s); } public void setSameSchemeRelativeReferences(String scheme) { if (scheme.equals("*")) backwardCompatibleRelativeRefs = new AbstractSet<String>(){ @Override public int size() { return Integer.MAX_VALUE; } @Override public Iterator<String> iterator() { throw new UnsupportedOperationException(); } @Override public boolean add(String o) { return false; } @Override public boolean contains(Object o) { return true; } }; else backwardCompatibleRelativeRefs.add(scheme.toLowerCase()); } protected void useSpec(String name, boolean asErr) { initializing(); Specification spec = Specification.get(name); specs.add(spec); for (int i=0; i<Force.SIZE; i++) { if (asErrors[i] || (asWarnings[i] && asErr)) { errors |= spec.getErrors(i); } if (asWarnings[i] ) { warnings |= spec.getErrors(i); } } prohibited |= spec.getProhibited(); required |= spec.getRequired(); warnings &= ~errors; } public SchemeSpecificPart getScheme(String scheme, Parser parser) { scheme = scheme.toLowerCase(); SchemeSpecificPart p = schemes.get(scheme); if (p!=null) { p.usedBy(parser); return p; } int dash = scheme.indexOf('-'); if (dash != -1) { if (scheme.startsWith("x-")) { p = noScheme(); } else { if (nonIETFScheme==null) nonIETFScheme = new NoScheme() { @Override void usedBy(Parser pp) { pp.recordError(SCHEME,UNREGISTERED_NONIETF_SCHEME_TREE); } }; p = nonIETFScheme; } } else if (Specification.schemes.containsKey(scheme)) { SchemeSpecification spec = (SchemeSpecification)Specification.schemes.get(scheme); p = new NoScheme(spec.port); } else{ if (unregisteredScheme==null){ unregisteredScheme = new NoScheme() { @Override void usedBy(Parser pp) { pp.recordError(SCHEME,UNREGISTERED_IANA_SCHEME); } }; } p= unregisteredScheme; } p.usedBy(parser); // System.err.println("Scheme: "+scheme); if (schemes.size() < 1000) schemes.put(scheme,p); return p; } private NoScheme unregisteredScheme=null; private NoScheme nonIETFScheme=null; public SchemeSpecificPart noScheme() { return noScheme; } private class WithScheme extends SchemeSpecificPart { long zerrors; long zwarnings; int zrequired; int zprohibited; boolean inited = false; final SchemeSpecification scheme; private WithScheme(WithScheme ws) { zerrors = ws.zerrors; zwarnings = ws.zwarnings; zprohibited = ws.zprohibited; zrequired = ws.zrequired; scheme = ws.scheme; } private WithScheme(SchemeSpecification spec, boolean asErr){ scheme = spec; for (int i=0; i<Force.SIZE; i++) { if (asErrors[i] || (asWarnings[i] && asErr)) { zerrors |= spec.getErrors(i); } if (asWarnings[i] ) { zwarnings |= spec.getErrors(i); } } } @Override void usedBy(Parser parser) { if (!inited) { inited = true; zerrors |= errors; zwarnings |= warnings; zwarnings &= ~zerrors; zrequired = scheme.getRequired() | required; zprohibited = scheme.getProhibited() | prohibited; } } @Override public long getMask(boolean includeWarnings) { return includeWarnings?(zerrors|zwarnings):zerrors; } @Override public int getRequired() { return zrequired; } @Override public int getProhibited() { return zprohibited; } @Override public void analyse(Parser parser, int range) { scheme.analyse(parser,range); } @Override public int port() { return scheme.port; } @Override public boolean withScheme() { return true; } } private class NoScheme extends SchemeSpecificPart { NoScheme() { this(-1); } final private int port; NoScheme(int i) { port = i; } @Override public long getMask(boolean includeWarnings) { return IRIFactoryImpl.this.getMask(includeWarnings); } @Override public int getRequired() { return IRIFactoryImpl.this.getRequired(); } @Override public int getProhibited() { return IRIFactoryImpl.this.getProhibited(); } @Override void usedBy(Parser parser) { /* nothing */ } @Override public void analyse(Parser parser, int range) {/* nothing */ } @Override public int port() { return port; } @Override public boolean withScheme() { return false; } } final private NoScheme noScheme = new NoScheme(); private int required = 0; private int prohibited = 0; public int getRequired() { return required; } public int getProhibited() { return prohibited ; } final private Map<String, SchemeSpecificPart> schemes = new HashMap<>(); public void useSchemeSpecificRules(String scheme, boolean asErr) { if (scheme.equals("*")) { for ( String s : Specification.schemes.keySet() ) { scheme = s; if ( !schemes.containsKey( scheme ) ) { useSchemeSpecificRules( scheme, asErr ); } } return ; } scheme = scheme.toLowerCase() ; SchemeSpecification spec = (SchemeSpecification) Specification.schemes.get(scheme) ; if (spec == null) { schemes.put(scheme, noScheme) ; } else { schemes.put(scheme, new WithScheme(spec, asErr)) ; } } }
744_5
/* * 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.dhcprelay; import org.onlab.packet.BasePacket; import org.onlab.packet.DHCP6; import org.onlab.packet.DHCP6.MsgType; import org.onlab.packet.Ip6Address; import org.onlab.packet.IpAddress; import org.onlab.packet.VlanId; import org.onlab.packet.dhcp.Dhcp6ClientIdOption; import org.onlab.packet.dhcp.Dhcp6RelayOption; import org.onlab.packet.dhcp.Dhcp6Option; import org.onlab.packet.Ethernet; import org.onlab.packet.IPv6; import org.onlab.packet.MacAddress; import org.onlab.packet.UDP; import org.onlab.util.HexString; import org.onosproject.dhcprelay.api.DhcpServerInfo; import org.onosproject.dhcprelay.store.DhcpRelayCounters; import org.onosproject.net.ConnectPoint; import org.onosproject.net.host.InterfaceIpAddress; import org.onosproject.net.intf.Interface; import org.onosproject.net.packet.PacketContext; import org.onosproject.net.DeviceId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.List; import java.util.ArrayList; import org.onosproject.net.intf.InterfaceService; import org.onosproject.net.Host; import org.onosproject.net.host.HostService; import org.onosproject.net.HostLocation; import static com.google.common.base.Preconditions.checkNotNull; public final class Dhcp6HandlerUtil { private static final Logger log = LoggerFactory.getLogger(Dhcp6HandlerUtil.class); private Dhcp6HandlerUtil() { } // Returns the first v6 interface ip out of a set of interfaces or null. // Checks all interfaces, and ignores v6 interface ips public static Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) { for (Interface intf : intfs) { for (InterfaceIpAddress ip : intf.ipAddressesList()) { Ip6Address relayAgentIp = ip.ipAddress().getIp6Address(); if (relayAgentIp != null) { return relayAgentIp; } } } return null; } /** * Returns the first interface ip from interface. * * @param iface interface of one connect point * @return the first interface IP; null if not exists an IP address in * these interfaces */ private static Ip6Address getFirstIpFromInterface(Interface iface) { checkNotNull(iface, "Interface can't be null"); return iface.ipAddressesList().stream() .map(InterfaceIpAddress::ipAddress) .filter(IpAddress::isIp6) .map(IpAddress::getIp6Address) .findFirst() .orElse(null); } /** * * process the LQ reply packet from dhcp server. * * @param defaultServerInfoList default server list * @param indirectServerInfoList default indirect server list * @param serverInterface server interface * @param interfaceService interface service * @param hostService host service * @param context packet context * @param receivedPacket server ethernet packet * @param recevingInterfaces set of server side interfaces * @return a packet ready to be sent to relevant output interface */ public static InternalPacket processLQ6PacketFromServer( List<DhcpServerInfo> defaultServerInfoList, List<DhcpServerInfo> indirectServerInfoList, Interface serverInterface, InterfaceService interfaceService, HostService hostService, PacketContext context, Ethernet receivedPacket, Set<Interface> recevingInterfaces) { // get dhcp6 header. Ethernet etherReply = (Ethernet) receivedPacket.clone(); IPv6 ipv6Packet = (IPv6) etherReply.getPayload(); UDP udpPacket = (UDP) ipv6Packet.getPayload(); DHCP6 lq6Reply = (DHCP6) udpPacket.getPayload(); // TODO: refactor ConnectPoint receivedFrom = context.inPacket().receivedFrom(); DeviceId receivedFromDevice = receivedFrom.deviceId(); DhcpServerInfo serverInfo; Ip6Address dhcpServerIp = null; ConnectPoint dhcpServerConnectPoint = null; MacAddress dhcpConnectMac = null; VlanId dhcpConnectVlan = null; Ip6Address dhcpGatewayIp = null; // todo: refactor Ip6Address indirectDhcpServerIp = null; ConnectPoint indirectDhcpServerConnectPoint = null; MacAddress indirectDhcpConnectMac = null; VlanId indirectDhcpConnectVlan = null; Ip6Address indirectDhcpGatewayIp = null; Ip6Address indirectRelayAgentIpFromCfg = null; if (!defaultServerInfoList.isEmpty()) { serverInfo = defaultServerInfoList.get(0); dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null); dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null); dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null); dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null); dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null); } if (!indirectServerInfoList.isEmpty()) { serverInfo = indirectServerInfoList.get(0); indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null); indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null); indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null); indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null); indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null); indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6(receivedFromDevice).orElse(null); } Boolean directConnFlag = directlyConnected(lq6Reply); ConnectPoint inPort = context.inPacket().receivedFrom(); if ((directConnFlag || indirectDhcpServerIp == null) && !inPort.equals(dhcpServerConnectPoint)) { log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null", inPort, dhcpServerConnectPoint); return null; } if (!directConnFlag && indirectDhcpServerIp != null && !inPort.equals(indirectDhcpServerConnectPoint)) { log.warn("Receiving port {} is not the same as server connect point {} for indirect", inPort, indirectDhcpServerConnectPoint); return null; } Ip6Address nextHopIP = Ip6Address.valueOf(ipv6Packet.getDestinationAddress()); // use hosts store to find out the next hop mac and connection point Set<Host> hosts = hostService.getHostsByIp(nextHopIP); Host host; if (!hosts.isEmpty()) { host = hosts.iterator().next(); } else { log.warn("Host {} is not in store", nextHopIP); return null; } HostLocation hl = host.location(); String clientConnectionPointStr = hl.toString(); // iterator().next()); ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr); VlanId originalPacketVlanId = VlanId.vlanId(etherReply.getVlanID()); Interface iface; iface = interfaceService.getInterfacesByPort(clientConnectionPoint) .stream() .filter(iface1 -> interfaceContainsVlan(iface1, originalPacketVlanId)) .findFirst() .orElse(null); etherReply.setSourceMACAddress(iface.mac()); etherReply.setDestinationMACAddress(host.mac()); // workaround for a bug where core sends src port as 547 (server) udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT); udpPacket.setPayload(lq6Reply); udpPacket.resetChecksum(); ipv6Packet.setPayload(udpPacket); etherReply.setPayload(ipv6Packet); return InternalPacket.internalPacket(etherReply, clientConnectionPoint); } /** * extract DHCP6 payload from dhcp6 relay message within relay-forwrd/reply. * * @param dhcp6 dhcp6 relay-reply or relay-forward * @return dhcp6Packet dhcp6 packet extracted from relay-message */ public static DHCP6 dhcp6PacketFromRelayPacket(DHCP6 dhcp6) { // extract the relay message if exist DHCP6 dhcp6Payload = dhcp6.getOptions().stream() .filter(opt -> opt instanceof Dhcp6RelayOption) .map(BasePacket::getPayload) .map(pld -> (DHCP6) pld) .findFirst() .orElse(null); if (dhcp6Payload == null) { // Can't find dhcp payload log.debug("Can't find dhcp6 payload from relay message"); } else { log.debug("dhcp6 payload found from relay message {}", dhcp6Payload); } return dhcp6Payload; } /** * find the leaf DHCP6 packet from multi-level relay packet. * * @param relayPacket dhcp6 relay packet * @return leafPacket non-relay dhcp6 packet */ public static DHCP6 getDhcp6Leaf(DHCP6 relayPacket) { DHCP6 dhcp6Parent = relayPacket; DHCP6 dhcp6Child = null; log.debug("getDhcp6Leaf entered."); while (dhcp6Parent != null) { dhcp6Child = dhcp6PacketFromRelayPacket(dhcp6Parent); if (dhcp6Child != null) { if (dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() && dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) { log.debug("leaf dhcp6 packet found."); break; } else { // found another relay, go for another loop dhcp6Parent = dhcp6Child; } } else { log.debug("Expected dhcp6 within relay pkt, but no dhcp6 leaf found."); break; } } return dhcp6Child; } /** * Determine DHCP message type (direct DHCPv6 or wrapped into relay messages). * * @param relayPacket {@link DHCP6} packet to be parsed * @return {@link DHCP6.MsgType} contained message type of dhcpv6 packet/relay-message */ public static DHCP6.MsgType getDhcp6LeafMessageType(DHCP6 relayPacket) { checkNotNull(relayPacket); DHCP6 dhcp6Child = getDhcp6Leaf(relayPacket); return DHCP6.MsgType.getType(dhcp6Child != null ? dhcp6Child.getMsgType() : relayPacket.getMsgType()); } /** * check if DHCP6 relay-reply is reply. * * @param relayPacket dhcp6 relay-reply * @return boolean relay-reply contains ack */ public static boolean isDhcp6Reply(DHCP6 relayPacket) { DHCP6 leafDhcp6 = getDhcp6Leaf(relayPacket); if (leafDhcp6 != null) { if (leafDhcp6.getMsgType() == DHCP6.MsgType.REPLY.value()) { log.debug("isDhcp6Reply true."); return true; // must be directly connected } else { log.debug("isDhcp6Reply false. leaf dhcp6 is not replay. MsgType {}", leafDhcp6.getMsgType()); } } else { log.debug("isDhcp6Reply false. Expected dhcp6 within relay pkt but not found."); } log.debug("isDhcp6Reply false."); return false; } /** * check if DHCP6 is release or relay-forward contains release. * * @param dhcp6Payload dhcp6 packet * @return boolean dhcp6 contains release */ public static boolean isDhcp6Release(DHCP6 dhcp6Payload) { if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELEASE.value()) { log.debug("isDhcp6Release true."); return true; // must be directly connected } else { DHCP6 dhcp6Leaf = getDhcp6Leaf(dhcp6Payload); if (dhcp6Leaf != null) { if (dhcp6Leaf.getMsgType() == DHCP6.MsgType.RELEASE.value()) { log.debug("isDhcp6Release true. indirectlry connected"); return true; } else { log.debug("leaf dhcp6 is not release. MsgType {}", dhcp6Leaf.getMsgType()); return false; } } else { log.debug("isDhcp6Release false. dhcp6 is niether relay nor release."); return false; } } } /** * convert dhcp6 msgType to String. * * @param msgTypeVal msgType byte of dhcp6 packet * @return String string value of dhcp6 msg type */ public static String getMsgTypeStr(byte msgTypeVal) { MsgType msgType = DHCP6.MsgType.getType(msgTypeVal); return DHCP6.MsgType.getMsgTypeStr(msgType); } /** * find the string of dhcp6 leaf packets's msg type. * * @param directConnFlag boolean value indicating direct/indirect connection * @param dhcp6Packet dhcp6 packet * @return String string value of dhcp6 leaf packet msg type */ public static String findLeafMsgType(boolean directConnFlag, DHCP6 dhcp6Packet) { if (directConnFlag) { return getMsgTypeStr(dhcp6Packet.getMsgType()); } else { DHCP6 leafDhcp = getDhcp6Leaf(dhcp6Packet); if (leafDhcp != null) { return getMsgTypeStr(leafDhcp.getMsgType()); } else { return DhcpRelayCounters.INVALID_PACKET; } } } /** * Determind if an Interface contains a vlan id. * * @param iface the Interface * @param vlanId the vlan id * @return true if the Interface contains the vlan id */ public static boolean interfaceContainsVlan(Interface iface, VlanId vlanId) { if (vlanId.equals(VlanId.NONE)) { // untagged packet, check if vlan untagged or vlan native is not NONE return !iface.vlanUntagged().equals(VlanId.NONE) || !iface.vlanNative().equals(VlanId.NONE); } // tagged packet, check if the interface contains the vlan return iface.vlanTagged().contains(vlanId); } /** * Check if the host is directly connected to the network or not. * * @param dhcp6Payload the dhcp6 payload * @return true if the host is directly connected to the network; false otherwise */ public static boolean directlyConnected(DHCP6 dhcp6Payload) { log.debug("directlyConnected enters"); if (dhcp6Payload.getMsgType() == DHCP6.MsgType.LEASEQUERY.value() || dhcp6Payload.getMsgType() == DHCP6.MsgType.LEASEQUERY_REPLY.value()) { log.debug("directlyConnected false. MsgType {}", dhcp6Payload.getMsgType()); return false; } if (dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() && dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) { log.debug("directlyConnected true. MsgType {}", dhcp6Payload.getMsgType()); return true; } // Regardless of relay-forward or relay-replay, check if we see another relay message DHCP6 dhcp6Payload2 = dhcp6PacketFromRelayPacket(dhcp6Payload); if (dhcp6Payload2 != null) { if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELAY_FORW.value()) { log.debug("directlyConnected false. 1st relay-forward, 2nd MsgType {}", dhcp6Payload2.getMsgType()); return false; } else { // relay-reply if (dhcp6Payload2.getMsgType() != DHCP6.MsgType.RELAY_REPL.value() && dhcp6Payload2.getMsgType() != MsgType.LEASEQUERY_REPLY.value()) { log.debug("directlyConnected true. 2nd MsgType {}", dhcp6Payload2.getMsgType()); return true; // must be directly connected } else { log.debug("directlyConnected false. 1st relay-reply, 2nd relay-reply MsgType {}", dhcp6Payload2.getMsgType()); return false; // must be indirectly connected } } } else { log.debug("directlyConnected true."); return true; } } /** * Check if a given server info has v6 ipaddress. * * @param serverInfo server info to check * @return true if server info has v6 ip address; false otherwise */ public static boolean isServerIpEmpty(DhcpServerInfo serverInfo) { if (!serverInfo.getDhcpServerIp6().isPresent()) { log.warn("DhcpServerIp not available, use default DhcpServerIp {}", HexString.toHexString(serverInfo.getDhcpServerIp6().get().toOctets())); return true; } return false; } private static boolean isConnectMacEmpty(DhcpServerInfo serverInfo, Set<Interface> clientInterfaces) { if (!serverInfo.getDhcpConnectMac().isPresent()) { log.warn("DHCP6 {} not yet resolved .. Aborting DHCP " + "packet processing from client on port: {}", !serverInfo.getDhcpGatewayIp6().isPresent() ? "server IP " + serverInfo.getDhcpServerIp6() : "gateway IP " + serverInfo.getDhcpGatewayIp6(), clientInterfaces.iterator().next().connectPoint()); return true; } return false; } private static Dhcp6Option getInterfaceIdIdOption(PacketContext context, Ethernet clientPacket) { String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":"; Dhcp6Option interfaceId = new Dhcp6Option(); interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value()); byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress(); byte[] inPortStringBytes = inPortString.getBytes(); byte[] vlanIdBytes = new byte[2]; vlanIdBytes[0] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff); vlanIdBytes[1] = (byte) (clientPacket.getVlanID() & 0xff); byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length + inPortStringBytes.length + vlanIdBytes.length]; log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}", interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length, vlanIdBytes.length); System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length); System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length); System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length, vlanIdBytes.length); interfaceId.setData(interfaceIdBytes); interfaceId.setLength((short) interfaceIdBytes.length); log.debug("interfaceId write srcMac {} portString {}, vlanId {}", HexString.toHexString(clientSoureMacBytes, ":"), inPortString, vlanIdBytes); return interfaceId; } private static void addDhcp6OptionsFromClient(List<Dhcp6Option> options, byte[] dhcp6PacketByte, PacketContext context, Ethernet clientPacket) { Dhcp6Option relayMessage = new Dhcp6Option(); relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value()); relayMessage.setLength((short) dhcp6PacketByte.length); relayMessage.setData(dhcp6PacketByte); options.add(relayMessage); // create interfaceId option Dhcp6Option interfaceId = getInterfaceIdIdOption(context, clientPacket); options.add(interfaceId); } /** * build the DHCP6 solicit/request packet with gatewayip. * * @param context packet context * @param clientPacket client ethernet packet * @param clientInterfaces set of client side interfaces * @param serverInfo target server which a packet is generated for * @param serverInterface target server interface * @return ethernet packet with dhcp6 packet info */ public static Ethernet buildDhcp6PacketFromClient(PacketContext context, Ethernet clientPacket, Set<Interface> clientInterfaces, DhcpServerInfo serverInfo, Interface serverInterface) { ConnectPoint receivedFrom = context.inPacket().receivedFrom(); DeviceId receivedFromDevice = receivedFrom.deviceId(); Ip6Address relayAgentIp = getRelayAgentIPv6Address(clientInterfaces); MacAddress relayAgentMac = clientInterfaces.iterator().next().mac(); if (relayAgentIp == null || relayAgentMac == null) { log.warn("Missing DHCP relay agent interface Ipv6 addr config for " + "packet from client on port: {}. Aborting packet processing", clientInterfaces.iterator().next().connectPoint()); return null; } IPv6 clientIpv6 = (IPv6) clientPacket.getPayload(); UDP clientUdp = (UDP) clientIpv6.getPayload(); DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload(); boolean directConnFlag = directlyConnected(clientDhcp6); Ip6Address serverIpFacing = getFirstIpFromInterface(serverInterface); if (serverIpFacing == null || serverInterface.mac() == null) { log.warn("No IP v6 address for server Interface {}", serverInterface); return null; } Ethernet etherReply = clientPacket.duplicate(); etherReply.setSourceMACAddress(serverInterface.mac()); // set default info and replace with indirect if available later on. if (serverInfo.getDhcpConnectMac().isPresent()) { etherReply.setDestinationMACAddress(serverInfo.getDhcpConnectMac().get()); } if (serverInfo.getDhcpConnectVlan().isPresent()) { etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort()); } IPv6 ipv6Packet = (IPv6) etherReply.getPayload(); byte[] peerAddress = clientIpv6.getSourceAddress(); ipv6Packet.setSourceAddress(serverIpFacing.toOctets()); ipv6Packet.setDestinationAddress(serverInfo.getDhcpServerIp6().get().toOctets()); UDP udpPacket = (UDP) ipv6Packet.getPayload(); udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT); DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload(); byte[] dhcp6PacketByte = dhcp6Packet.serialize(); DHCP6 dhcp6Relay = new DHCP6(); dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value()); if (directConnFlag) { dhcp6Relay.setLinkAddress(relayAgentIp.toOctets()); } else { if (isServerIpEmpty(serverInfo)) { log.warn("indirect DhcpServerIp empty... use default server "); } else { // Indirect case, replace destination to indirect dhcp server if exist // Check if mac is obtained for valid server ip if (isConnectMacEmpty(serverInfo, clientInterfaces)) { log.warn("indirect Dhcp ConnectMac empty ..."); return null; } etherReply.setDestinationMACAddress(serverInfo.getDhcpConnectMac().get()); etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort()); ipv6Packet.setDestinationAddress(serverInfo.getDhcpServerIp6().get().toOctets()); } if (!serverInfo.getRelayAgentIp6(receivedFromDevice).isPresent()) { log.debug("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}", HexString.toHexString(relayAgentIp.toOctets(), ":")); serverIpFacing = relayAgentIp; } else { serverIpFacing = serverInfo.getRelayAgentIp6(receivedFromDevice).get(); } log.debug("Source IP address set as relay agent IP with value: {}", serverIpFacing); dhcp6Relay.setLinkAddress(serverIpFacing.toOctets()); ipv6Packet.setSourceAddress(serverIpFacing.toOctets()); } // peer address: address of the client or relay agent from which the message to be relayed was received. dhcp6Relay.setPeerAddress(peerAddress); // directly connected case, hop count is zero; otherwise, hop count + 1 if (directConnFlag) { dhcp6Relay.setHopCount((byte) 0); } else { dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1)); } List<Dhcp6Option> options = new ArrayList<>(); addDhcp6OptionsFromClient(options, dhcp6PacketByte, context, clientPacket); dhcp6Relay.setOptions(options); udpPacket.setPayload(dhcp6Relay); udpPacket.resetChecksum(); ipv6Packet.setPayload(udpPacket); ipv6Packet.setHopLimit((byte) 64); etherReply.setPayload(ipv6Packet); return etherReply; } /** * build the DHCP6 solicit/request packet with gatewayip. * * @param directConnFlag flag indicating if packet is from direct client or not * @param serverInfo server to check its connect point * @return boolean true if serverInfo is found; false otherwise */ public static boolean checkDhcpServerConnPt(boolean directConnFlag, DhcpServerInfo serverInfo) { if (serverInfo.getDhcpServerConnectPoint() == null) { log.warn("DHCP6 server connect point for {} connPt {}", directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint()); return false; } return true; } /** * extract from dhcp6 packet ClientIdOption. * * @param directConnFlag directly connected host * @param dhcp6Payload the dhcp6 payload * @return Dhcp6ClientIdOption clientIdOption, or null if not exists. */ static Dhcp6ClientIdOption extractClientId(Boolean directConnFlag, DHCP6 dhcp6Payload) { Dhcp6ClientIdOption clientIdOption; if (directConnFlag) { clientIdOption = dhcp6Payload.getOptions() .stream() .filter(opt -> opt instanceof Dhcp6ClientIdOption) .map(opt -> (Dhcp6ClientIdOption) opt) .findFirst() .orElse(null); } else { DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(dhcp6Payload); clientIdOption = leafDhcp.getOptions() .stream() .filter(opt -> opt instanceof Dhcp6ClientIdOption) .map(opt -> (Dhcp6ClientIdOption) opt) .findFirst() .orElse(null); } return clientIdOption; } }
opennetworkinglab/onos
apps/dhcprelay/app/src/main/java/org/onosproject/dhcprelay/Dhcp6HandlerUtil.java
7,032
// get dhcp6 header.
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.dhcprelay; import org.onlab.packet.BasePacket; import org.onlab.packet.DHCP6; import org.onlab.packet.DHCP6.MsgType; import org.onlab.packet.Ip6Address; import org.onlab.packet.IpAddress; import org.onlab.packet.VlanId; import org.onlab.packet.dhcp.Dhcp6ClientIdOption; import org.onlab.packet.dhcp.Dhcp6RelayOption; import org.onlab.packet.dhcp.Dhcp6Option; import org.onlab.packet.Ethernet; import org.onlab.packet.IPv6; import org.onlab.packet.MacAddress; import org.onlab.packet.UDP; import org.onlab.util.HexString; import org.onosproject.dhcprelay.api.DhcpServerInfo; import org.onosproject.dhcprelay.store.DhcpRelayCounters; import org.onosproject.net.ConnectPoint; import org.onosproject.net.host.InterfaceIpAddress; import org.onosproject.net.intf.Interface; import org.onosproject.net.packet.PacketContext; import org.onosproject.net.DeviceId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.List; import java.util.ArrayList; import org.onosproject.net.intf.InterfaceService; import org.onosproject.net.Host; import org.onosproject.net.host.HostService; import org.onosproject.net.HostLocation; import static com.google.common.base.Preconditions.checkNotNull; public final class Dhcp6HandlerUtil { private static final Logger log = LoggerFactory.getLogger(Dhcp6HandlerUtil.class); private Dhcp6HandlerUtil() { } // Returns the first v6 interface ip out of a set of interfaces or null. // Checks all interfaces, and ignores v6 interface ips public static Ip6Address getRelayAgentIPv6Address(Set<Interface> intfs) { for (Interface intf : intfs) { for (InterfaceIpAddress ip : intf.ipAddressesList()) { Ip6Address relayAgentIp = ip.ipAddress().getIp6Address(); if (relayAgentIp != null) { return relayAgentIp; } } } return null; } /** * Returns the first interface ip from interface. * * @param iface interface of one connect point * @return the first interface IP; null if not exists an IP address in * these interfaces */ private static Ip6Address getFirstIpFromInterface(Interface iface) { checkNotNull(iface, "Interface can't be null"); return iface.ipAddressesList().stream() .map(InterfaceIpAddress::ipAddress) .filter(IpAddress::isIp6) .map(IpAddress::getIp6Address) .findFirst() .orElse(null); } /** * * process the LQ reply packet from dhcp server. * * @param defaultServerInfoList default server list * @param indirectServerInfoList default indirect server list * @param serverInterface server interface * @param interfaceService interface service * @param hostService host service * @param context packet context * @param receivedPacket server ethernet packet * @param recevingInterfaces set of server side interfaces * @return a packet ready to be sent to relevant output interface */ public static InternalPacket processLQ6PacketFromServer( List<DhcpServerInfo> defaultServerInfoList, List<DhcpServerInfo> indirectServerInfoList, Interface serverInterface, InterfaceService interfaceService, HostService hostService, PacketContext context, Ethernet receivedPacket, Set<Interface> recevingInterfaces) { // get dhcp6<SUF> Ethernet etherReply = (Ethernet) receivedPacket.clone(); IPv6 ipv6Packet = (IPv6) etherReply.getPayload(); UDP udpPacket = (UDP) ipv6Packet.getPayload(); DHCP6 lq6Reply = (DHCP6) udpPacket.getPayload(); // TODO: refactor ConnectPoint receivedFrom = context.inPacket().receivedFrom(); DeviceId receivedFromDevice = receivedFrom.deviceId(); DhcpServerInfo serverInfo; Ip6Address dhcpServerIp = null; ConnectPoint dhcpServerConnectPoint = null; MacAddress dhcpConnectMac = null; VlanId dhcpConnectVlan = null; Ip6Address dhcpGatewayIp = null; // todo: refactor Ip6Address indirectDhcpServerIp = null; ConnectPoint indirectDhcpServerConnectPoint = null; MacAddress indirectDhcpConnectMac = null; VlanId indirectDhcpConnectVlan = null; Ip6Address indirectDhcpGatewayIp = null; Ip6Address indirectRelayAgentIpFromCfg = null; if (!defaultServerInfoList.isEmpty()) { serverInfo = defaultServerInfoList.get(0); dhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null); dhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null); dhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null); dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null); dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null); } if (!indirectServerInfoList.isEmpty()) { serverInfo = indirectServerInfoList.get(0); indirectDhcpConnectMac = serverInfo.getDhcpConnectMac().orElse(null); indirectDhcpGatewayIp = serverInfo.getDhcpGatewayIp6().orElse(null); indirectDhcpServerIp = serverInfo.getDhcpServerIp6().orElse(null); indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null); indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null); indirectRelayAgentIpFromCfg = serverInfo.getRelayAgentIp6(receivedFromDevice).orElse(null); } Boolean directConnFlag = directlyConnected(lq6Reply); ConnectPoint inPort = context.inPacket().receivedFrom(); if ((directConnFlag || indirectDhcpServerIp == null) && !inPort.equals(dhcpServerConnectPoint)) { log.warn("Receiving port {} is not the same as server connect point {} for direct or indirect-null", inPort, dhcpServerConnectPoint); return null; } if (!directConnFlag && indirectDhcpServerIp != null && !inPort.equals(indirectDhcpServerConnectPoint)) { log.warn("Receiving port {} is not the same as server connect point {} for indirect", inPort, indirectDhcpServerConnectPoint); return null; } Ip6Address nextHopIP = Ip6Address.valueOf(ipv6Packet.getDestinationAddress()); // use hosts store to find out the next hop mac and connection point Set<Host> hosts = hostService.getHostsByIp(nextHopIP); Host host; if (!hosts.isEmpty()) { host = hosts.iterator().next(); } else { log.warn("Host {} is not in store", nextHopIP); return null; } HostLocation hl = host.location(); String clientConnectionPointStr = hl.toString(); // iterator().next()); ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr); VlanId originalPacketVlanId = VlanId.vlanId(etherReply.getVlanID()); Interface iface; iface = interfaceService.getInterfacesByPort(clientConnectionPoint) .stream() .filter(iface1 -> interfaceContainsVlan(iface1, originalPacketVlanId)) .findFirst() .orElse(null); etherReply.setSourceMACAddress(iface.mac()); etherReply.setDestinationMACAddress(host.mac()); // workaround for a bug where core sends src port as 547 (server) udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT); udpPacket.setPayload(lq6Reply); udpPacket.resetChecksum(); ipv6Packet.setPayload(udpPacket); etherReply.setPayload(ipv6Packet); return InternalPacket.internalPacket(etherReply, clientConnectionPoint); } /** * extract DHCP6 payload from dhcp6 relay message within relay-forwrd/reply. * * @param dhcp6 dhcp6 relay-reply or relay-forward * @return dhcp6Packet dhcp6 packet extracted from relay-message */ public static DHCP6 dhcp6PacketFromRelayPacket(DHCP6 dhcp6) { // extract the relay message if exist DHCP6 dhcp6Payload = dhcp6.getOptions().stream() .filter(opt -> opt instanceof Dhcp6RelayOption) .map(BasePacket::getPayload) .map(pld -> (DHCP6) pld) .findFirst() .orElse(null); if (dhcp6Payload == null) { // Can't find dhcp payload log.debug("Can't find dhcp6 payload from relay message"); } else { log.debug("dhcp6 payload found from relay message {}", dhcp6Payload); } return dhcp6Payload; } /** * find the leaf DHCP6 packet from multi-level relay packet. * * @param relayPacket dhcp6 relay packet * @return leafPacket non-relay dhcp6 packet */ public static DHCP6 getDhcp6Leaf(DHCP6 relayPacket) { DHCP6 dhcp6Parent = relayPacket; DHCP6 dhcp6Child = null; log.debug("getDhcp6Leaf entered."); while (dhcp6Parent != null) { dhcp6Child = dhcp6PacketFromRelayPacket(dhcp6Parent); if (dhcp6Child != null) { if (dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() && dhcp6Child.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) { log.debug("leaf dhcp6 packet found."); break; } else { // found another relay, go for another loop dhcp6Parent = dhcp6Child; } } else { log.debug("Expected dhcp6 within relay pkt, but no dhcp6 leaf found."); break; } } return dhcp6Child; } /** * Determine DHCP message type (direct DHCPv6 or wrapped into relay messages). * * @param relayPacket {@link DHCP6} packet to be parsed * @return {@link DHCP6.MsgType} contained message type of dhcpv6 packet/relay-message */ public static DHCP6.MsgType getDhcp6LeafMessageType(DHCP6 relayPacket) { checkNotNull(relayPacket); DHCP6 dhcp6Child = getDhcp6Leaf(relayPacket); return DHCP6.MsgType.getType(dhcp6Child != null ? dhcp6Child.getMsgType() : relayPacket.getMsgType()); } /** * check if DHCP6 relay-reply is reply. * * @param relayPacket dhcp6 relay-reply * @return boolean relay-reply contains ack */ public static boolean isDhcp6Reply(DHCP6 relayPacket) { DHCP6 leafDhcp6 = getDhcp6Leaf(relayPacket); if (leafDhcp6 != null) { if (leafDhcp6.getMsgType() == DHCP6.MsgType.REPLY.value()) { log.debug("isDhcp6Reply true."); return true; // must be directly connected } else { log.debug("isDhcp6Reply false. leaf dhcp6 is not replay. MsgType {}", leafDhcp6.getMsgType()); } } else { log.debug("isDhcp6Reply false. Expected dhcp6 within relay pkt but not found."); } log.debug("isDhcp6Reply false."); return false; } /** * check if DHCP6 is release or relay-forward contains release. * * @param dhcp6Payload dhcp6 packet * @return boolean dhcp6 contains release */ public static boolean isDhcp6Release(DHCP6 dhcp6Payload) { if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELEASE.value()) { log.debug("isDhcp6Release true."); return true; // must be directly connected } else { DHCP6 dhcp6Leaf = getDhcp6Leaf(dhcp6Payload); if (dhcp6Leaf != null) { if (dhcp6Leaf.getMsgType() == DHCP6.MsgType.RELEASE.value()) { log.debug("isDhcp6Release true. indirectlry connected"); return true; } else { log.debug("leaf dhcp6 is not release. MsgType {}", dhcp6Leaf.getMsgType()); return false; } } else { log.debug("isDhcp6Release false. dhcp6 is niether relay nor release."); return false; } } } /** * convert dhcp6 msgType to String. * * @param msgTypeVal msgType byte of dhcp6 packet * @return String string value of dhcp6 msg type */ public static String getMsgTypeStr(byte msgTypeVal) { MsgType msgType = DHCP6.MsgType.getType(msgTypeVal); return DHCP6.MsgType.getMsgTypeStr(msgType); } /** * find the string of dhcp6 leaf packets's msg type. * * @param directConnFlag boolean value indicating direct/indirect connection * @param dhcp6Packet dhcp6 packet * @return String string value of dhcp6 leaf packet msg type */ public static String findLeafMsgType(boolean directConnFlag, DHCP6 dhcp6Packet) { if (directConnFlag) { return getMsgTypeStr(dhcp6Packet.getMsgType()); } else { DHCP6 leafDhcp = getDhcp6Leaf(dhcp6Packet); if (leafDhcp != null) { return getMsgTypeStr(leafDhcp.getMsgType()); } else { return DhcpRelayCounters.INVALID_PACKET; } } } /** * Determind if an Interface contains a vlan id. * * @param iface the Interface * @param vlanId the vlan id * @return true if the Interface contains the vlan id */ public static boolean interfaceContainsVlan(Interface iface, VlanId vlanId) { if (vlanId.equals(VlanId.NONE)) { // untagged packet, check if vlan untagged or vlan native is not NONE return !iface.vlanUntagged().equals(VlanId.NONE) || !iface.vlanNative().equals(VlanId.NONE); } // tagged packet, check if the interface contains the vlan return iface.vlanTagged().contains(vlanId); } /** * Check if the host is directly connected to the network or not. * * @param dhcp6Payload the dhcp6 payload * @return true if the host is directly connected to the network; false otherwise */ public static boolean directlyConnected(DHCP6 dhcp6Payload) { log.debug("directlyConnected enters"); if (dhcp6Payload.getMsgType() == DHCP6.MsgType.LEASEQUERY.value() || dhcp6Payload.getMsgType() == DHCP6.MsgType.LEASEQUERY_REPLY.value()) { log.debug("directlyConnected false. MsgType {}", dhcp6Payload.getMsgType()); return false; } if (dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_FORW.value() && dhcp6Payload.getMsgType() != DHCP6.MsgType.RELAY_REPL.value()) { log.debug("directlyConnected true. MsgType {}", dhcp6Payload.getMsgType()); return true; } // Regardless of relay-forward or relay-replay, check if we see another relay message DHCP6 dhcp6Payload2 = dhcp6PacketFromRelayPacket(dhcp6Payload); if (dhcp6Payload2 != null) { if (dhcp6Payload.getMsgType() == DHCP6.MsgType.RELAY_FORW.value()) { log.debug("directlyConnected false. 1st relay-forward, 2nd MsgType {}", dhcp6Payload2.getMsgType()); return false; } else { // relay-reply if (dhcp6Payload2.getMsgType() != DHCP6.MsgType.RELAY_REPL.value() && dhcp6Payload2.getMsgType() != MsgType.LEASEQUERY_REPLY.value()) { log.debug("directlyConnected true. 2nd MsgType {}", dhcp6Payload2.getMsgType()); return true; // must be directly connected } else { log.debug("directlyConnected false. 1st relay-reply, 2nd relay-reply MsgType {}", dhcp6Payload2.getMsgType()); return false; // must be indirectly connected } } } else { log.debug("directlyConnected true."); return true; } } /** * Check if a given server info has v6 ipaddress. * * @param serverInfo server info to check * @return true if server info has v6 ip address; false otherwise */ public static boolean isServerIpEmpty(DhcpServerInfo serverInfo) { if (!serverInfo.getDhcpServerIp6().isPresent()) { log.warn("DhcpServerIp not available, use default DhcpServerIp {}", HexString.toHexString(serverInfo.getDhcpServerIp6().get().toOctets())); return true; } return false; } private static boolean isConnectMacEmpty(DhcpServerInfo serverInfo, Set<Interface> clientInterfaces) { if (!serverInfo.getDhcpConnectMac().isPresent()) { log.warn("DHCP6 {} not yet resolved .. Aborting DHCP " + "packet processing from client on port: {}", !serverInfo.getDhcpGatewayIp6().isPresent() ? "server IP " + serverInfo.getDhcpServerIp6() : "gateway IP " + serverInfo.getDhcpGatewayIp6(), clientInterfaces.iterator().next().connectPoint()); return true; } return false; } private static Dhcp6Option getInterfaceIdIdOption(PacketContext context, Ethernet clientPacket) { String inPortString = "-" + context.inPacket().receivedFrom().toString() + ":"; Dhcp6Option interfaceId = new Dhcp6Option(); interfaceId.setCode(DHCP6.OptionCode.INTERFACE_ID.value()); byte[] clientSoureMacBytes = clientPacket.getSourceMACAddress(); byte[] inPortStringBytes = inPortString.getBytes(); byte[] vlanIdBytes = new byte[2]; vlanIdBytes[0] = (byte) ((clientPacket.getVlanID() >> 8) & 0xff); vlanIdBytes[1] = (byte) (clientPacket.getVlanID() & 0xff); byte[] interfaceIdBytes = new byte[clientSoureMacBytes.length + inPortStringBytes.length + vlanIdBytes.length]; log.debug("Length: interfaceIdBytes {} clientSoureMacBytes {} inPortStringBytes {} vlan {}", interfaceIdBytes.length, clientSoureMacBytes.length, inPortStringBytes.length, vlanIdBytes.length); System.arraycopy(clientSoureMacBytes, 0, interfaceIdBytes, 0, clientSoureMacBytes.length); System.arraycopy(inPortStringBytes, 0, interfaceIdBytes, clientSoureMacBytes.length, inPortStringBytes.length); System.arraycopy(vlanIdBytes, 0, interfaceIdBytes, clientSoureMacBytes.length + inPortStringBytes.length, vlanIdBytes.length); interfaceId.setData(interfaceIdBytes); interfaceId.setLength((short) interfaceIdBytes.length); log.debug("interfaceId write srcMac {} portString {}, vlanId {}", HexString.toHexString(clientSoureMacBytes, ":"), inPortString, vlanIdBytes); return interfaceId; } private static void addDhcp6OptionsFromClient(List<Dhcp6Option> options, byte[] dhcp6PacketByte, PacketContext context, Ethernet clientPacket) { Dhcp6Option relayMessage = new Dhcp6Option(); relayMessage.setCode(DHCP6.OptionCode.RELAY_MSG.value()); relayMessage.setLength((short) dhcp6PacketByte.length); relayMessage.setData(dhcp6PacketByte); options.add(relayMessage); // create interfaceId option Dhcp6Option interfaceId = getInterfaceIdIdOption(context, clientPacket); options.add(interfaceId); } /** * build the DHCP6 solicit/request packet with gatewayip. * * @param context packet context * @param clientPacket client ethernet packet * @param clientInterfaces set of client side interfaces * @param serverInfo target server which a packet is generated for * @param serverInterface target server interface * @return ethernet packet with dhcp6 packet info */ public static Ethernet buildDhcp6PacketFromClient(PacketContext context, Ethernet clientPacket, Set<Interface> clientInterfaces, DhcpServerInfo serverInfo, Interface serverInterface) { ConnectPoint receivedFrom = context.inPacket().receivedFrom(); DeviceId receivedFromDevice = receivedFrom.deviceId(); Ip6Address relayAgentIp = getRelayAgentIPv6Address(clientInterfaces); MacAddress relayAgentMac = clientInterfaces.iterator().next().mac(); if (relayAgentIp == null || relayAgentMac == null) { log.warn("Missing DHCP relay agent interface Ipv6 addr config for " + "packet from client on port: {}. Aborting packet processing", clientInterfaces.iterator().next().connectPoint()); return null; } IPv6 clientIpv6 = (IPv6) clientPacket.getPayload(); UDP clientUdp = (UDP) clientIpv6.getPayload(); DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload(); boolean directConnFlag = directlyConnected(clientDhcp6); Ip6Address serverIpFacing = getFirstIpFromInterface(serverInterface); if (serverIpFacing == null || serverInterface.mac() == null) { log.warn("No IP v6 address for server Interface {}", serverInterface); return null; } Ethernet etherReply = clientPacket.duplicate(); etherReply.setSourceMACAddress(serverInterface.mac()); // set default info and replace with indirect if available later on. if (serverInfo.getDhcpConnectMac().isPresent()) { etherReply.setDestinationMACAddress(serverInfo.getDhcpConnectMac().get()); } if (serverInfo.getDhcpConnectVlan().isPresent()) { etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort()); } IPv6 ipv6Packet = (IPv6) etherReply.getPayload(); byte[] peerAddress = clientIpv6.getSourceAddress(); ipv6Packet.setSourceAddress(serverIpFacing.toOctets()); ipv6Packet.setDestinationAddress(serverInfo.getDhcpServerIp6().get().toOctets()); UDP udpPacket = (UDP) ipv6Packet.getPayload(); udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT); DHCP6 dhcp6Packet = (DHCP6) udpPacket.getPayload(); byte[] dhcp6PacketByte = dhcp6Packet.serialize(); DHCP6 dhcp6Relay = new DHCP6(); dhcp6Relay.setMsgType(DHCP6.MsgType.RELAY_FORW.value()); if (directConnFlag) { dhcp6Relay.setLinkAddress(relayAgentIp.toOctets()); } else { if (isServerIpEmpty(serverInfo)) { log.warn("indirect DhcpServerIp empty... use default server "); } else { // Indirect case, replace destination to indirect dhcp server if exist // Check if mac is obtained for valid server ip if (isConnectMacEmpty(serverInfo, clientInterfaces)) { log.warn("indirect Dhcp ConnectMac empty ..."); return null; } etherReply.setDestinationMACAddress(serverInfo.getDhcpConnectMac().get()); etherReply.setVlanID(serverInfo.getDhcpConnectVlan().get().toShort()); ipv6Packet.setDestinationAddress(serverInfo.getDhcpServerIp6().get().toOctets()); } if (!serverInfo.getRelayAgentIp6(receivedFromDevice).isPresent()) { log.debug("indirect connection: relayAgentIp NOT availale from config file! Use dynamic. {}", HexString.toHexString(relayAgentIp.toOctets(), ":")); serverIpFacing = relayAgentIp; } else { serverIpFacing = serverInfo.getRelayAgentIp6(receivedFromDevice).get(); } log.debug("Source IP address set as relay agent IP with value: {}", serverIpFacing); dhcp6Relay.setLinkAddress(serverIpFacing.toOctets()); ipv6Packet.setSourceAddress(serverIpFacing.toOctets()); } // peer address: address of the client or relay agent from which the message to be relayed was received. dhcp6Relay.setPeerAddress(peerAddress); // directly connected case, hop count is zero; otherwise, hop count + 1 if (directConnFlag) { dhcp6Relay.setHopCount((byte) 0); } else { dhcp6Relay.setHopCount((byte) (dhcp6Packet.getHopCount() + 1)); } List<Dhcp6Option> options = new ArrayList<>(); addDhcp6OptionsFromClient(options, dhcp6PacketByte, context, clientPacket); dhcp6Relay.setOptions(options); udpPacket.setPayload(dhcp6Relay); udpPacket.resetChecksum(); ipv6Packet.setPayload(udpPacket); ipv6Packet.setHopLimit((byte) 64); etherReply.setPayload(ipv6Packet); return etherReply; } /** * build the DHCP6 solicit/request packet with gatewayip. * * @param directConnFlag flag indicating if packet is from direct client or not * @param serverInfo server to check its connect point * @return boolean true if serverInfo is found; false otherwise */ public static boolean checkDhcpServerConnPt(boolean directConnFlag, DhcpServerInfo serverInfo) { if (serverInfo.getDhcpServerConnectPoint() == null) { log.warn("DHCP6 server connect point for {} connPt {}", directConnFlag ? "direct" : "indirect", serverInfo.getDhcpServerConnectPoint()); return false; } return true; } /** * extract from dhcp6 packet ClientIdOption. * * @param directConnFlag directly connected host * @param dhcp6Payload the dhcp6 payload * @return Dhcp6ClientIdOption clientIdOption, or null if not exists. */ static Dhcp6ClientIdOption extractClientId(Boolean directConnFlag, DHCP6 dhcp6Payload) { Dhcp6ClientIdOption clientIdOption; if (directConnFlag) { clientIdOption = dhcp6Payload.getOptions() .stream() .filter(opt -> opt instanceof Dhcp6ClientIdOption) .map(opt -> (Dhcp6ClientIdOption) opt) .findFirst() .orElse(null); } else { DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(dhcp6Payload); clientIdOption = leafDhcp.getOptions() .stream() .filter(opt -> opt instanceof Dhcp6ClientIdOption) .map(opt -> (Dhcp6ClientIdOption) opt) .findFirst() .orElse(null); } return clientIdOption; } }
752_5
/* * 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.netbeans.modules.refactoring.java.plugins; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.source.util.Trees; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.api.java.source.GeneratorUtilities; import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.TreePathHandle; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.modules.refactoring.java.api.MemberInfo; import org.netbeans.modules.refactoring.java.api.MemberInfo.Group; import org.netbeans.modules.refactoring.java.api.PullUpRefactoring; import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor; import org.netbeans.modules.refactoring.java.spi.ToPhaseException; /** * * @author Jan Becicka * @author Ralph Benjamin Ruijs */ public class PullUpTransformer extends RefactoringVisitor { private MemberInfo<ElementHandle<? extends Element>>[] members; private TypeElement targetType; private TypeElement sourceType; private PullUpRefactoring refactoring; public PullUpTransformer(PullUpRefactoring refactoring) { this.refactoring = refactoring; this.members = refactoring.getMembers(); } @Override public void setWorkingCopy(WorkingCopy copy) throws ToPhaseException { SourceUtils.forceSource(copy, refactoring.getSourceType().getFileObject()); super.setWorkingCopy(copy); this.targetType = refactoring.getTargetType().resolve(copy); this.sourceType = (TypeElement) refactoring.getSourceType().resolveElement(copy); } @Override public Tree visitClass(ClassTree tree, Element p) { Element classElement = workingCopy.getTrees().getElement(getCurrentPath()); GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy); // helper AtomicBoolean classIsAbstract = new AtomicBoolean(classElement.getKind().isInterface()); if (classElement.equals(targetType)) { addMembersToTarget(tree, classIsAbstract, targetType, genUtils); } else if (classElement.equals(sourceType)) { removeMembersFromSource(tree, classIsAbstract); } return super.visitClass(tree, p); } private void addMembersToTarget(ClassTree tree, AtomicBoolean classIsAbstract, TypeElement classElement, GeneratorUtilities genUtils) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { Element member = members[i].getElementHandle().resolve(workingCopy); if(member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } Group group = members[i].getGroup(); if (group == MemberInfo.Group.IMPLEMENTS) { njuClass = make.addClassImplementsClause(njuClass, make.QualIdent(member)); } else { if (members[i].isMakeAbstract()) { if (classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addAbstractMemberToTarget(njuClass, member, classElement, genUtils); } else { if (member.getModifiers().contains(Modifier.ABSTRACT) && classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addMemberToTarget(njuClass, member, classElement, group, genUtils); } } } if (njuClass != tree) { rewrite(tree, njuClass); } } private void removeMembersFromSource(ClassTree tree, AtomicBoolean classIsAbstract) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { if (members[i].getGroup() == MemberInfo.Group.IMPLEMENTS) { for (Tree t : njuClass.getImplementsClause()) { Element currentInterface = workingCopy.getTrees().getElement(TreePath.getPath(getCurrentPath(), t)); if (currentInterface != null && currentInterface.equals(members[i].getElementHandle().resolve(workingCopy))) { njuClass = make.removeClassImplementsClause(njuClass, t); rewrite(tree, njuClass); } } } else { Element current = workingCopy.getTrees().getElement(getCurrentPath()); Element member = members[i].getElementHandle().resolve(workingCopy); if(member != null && member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } if (member != null && member.getEnclosingElement().equals(current)) { if ((classIsAbstract.get() && !member.getModifiers().contains(Modifier.DEFAULT)) || !members[i].isMakeAbstract() || (member.getModifiers().contains(Modifier.ABSTRACT) && targetType.getKind().isInterface())) { // in case of interface always remove pulled method njuClass = make.removeClassMember(njuClass, workingCopy.getTrees().getTree(member)); rewrite(tree, njuClass); } else if (members[i].isMakeAbstract() && member.getModifiers().contains(Modifier.PRIVATE)) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(member); ModifiersTree mods = make.removeModifiersModifier(method.getModifiers(), Modifier.PRIVATE); mods = make.addModifiersModifier(mods, targetType.getKind().isInterface() ? Modifier.PUBLIC : Modifier.PROTECTED); rewrite(method.getModifiers(), mods); } } } } } private ClassTree addAbstractMemberToTarget(ClassTree njuClass, Element methodElm, Element classElement, GeneratorUtilities genUtils) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(methodElm); Set<Modifier> flags = method.getModifiers().getFlags(); Set<Modifier> mod = flags.isEmpty() ? EnumSet.noneOf(Modifier.class) : EnumSet.copyOf(flags); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); // abstract method cannot be default mod.remove(Modifier.DEFAULT); // abstract method cannot be synchronized mod.remove(Modifier.SYNCHRONIZED); if (classElement.getKind().isInterface()) { mod.remove(Modifier.PUBLIC); mod.remove(Modifier.PROTECTED); mod.remove(Modifier.PRIVATE); mod.remove(Modifier.ABSTRACT); } if (mod.contains(Modifier.PRIVATE)) { mod.remove(Modifier.PRIVATE); mod.add(Modifier.PROTECTED); } MethodTree newMethod = make.Method( make.Modifiers(mod), method.getName(), method.getReturnType(), method.getTypeParameters(), method.getParameters(), method.getThrows(), (BlockTree) null, (ExpressionTree) method.getDefaultValue()); newMethod = genUtils.importFQNs(newMethod); method = genUtils.importComments(method, workingCopy.getTrees().getPath(methodElm).getCompilationUnit()); genUtils.copyComments(method, newMethod, false); genUtils.copyComments(method, newMethod, true); njuClass = genUtils.insertClassMember(njuClass, newMethod); return njuClass; } private void makeClassAbstract(ClassTree njuClass) { Set<Modifier> mod = EnumSet.copyOf(njuClass.getModifiers().getFlags()); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); ModifiersTree modifiers = make.Modifiers(mod); rewrite(njuClass.getModifiers(), modifiers); } private ClassTree addMemberToTarget(ClassTree njuClass, Element member, TypeElement classElement, Group group, GeneratorUtilities genUtils) { TreePath mpath = workingCopy.getTrees().getPath(member); Tree memberTree = genUtils.importComments(mpath.getLeaf(), mpath.getCompilationUnit()); memberTree = genUtils.importFQNs(memberTree); memberTree = fixGenericTypes(memberTree, mpath, member); if (member.getModifiers().contains(Modifier.PRIVATE)) { Tree newMemberTree = null; if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); newMemberTree = make.Method( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); } else if (group == Group.FIELD) { VariableTree oldOne = (VariableTree) memberTree; newMemberTree = make.Variable( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getType(), oldOne.getInitializer()); } else if (group == Group.TYPE) { ClassTree oldOne = (ClassTree) memberTree; switch (member.getKind()) { case CLASS: newMemberTree = make.Class( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getExtendsClause(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case INTERFACE: newMemberTree = make.Interface( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case ANNOTATION_TYPE: newMemberTree = make.AnnotationType( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getMembers()); break; case ENUM: newMemberTree = make.Enum( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getImplementsClause(), oldOne.getMembers()); break; } } if (newMemberTree != null) { genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } } else { if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); ExecutableElement overriddenMethod = workingCopy.getElementUtilities().getOverriddenMethod((ExecutableElement) member); MethodTree newMemberTree = make.Method( overriddenMethod != null && workingCopy.getElementUtilities().isMemberOf(overriddenMethod, targetType)? oldOne.getModifiers() : removeAnnotations(workingCopy, make, oldOne.getModifiers(), mpath), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } else { njuClass = genUtils.insertClassMember(njuClass, memberTree); } } return njuClass; } static ModifiersTree removeAnnotations(WorkingCopy workingCopy, TreeMaker make,ModifiersTree oldOne, TreePath path) { TypeElement override = workingCopy.getElements().getTypeElement("java.lang.Override"); if(override == null) { return oldOne; } List<AnnotationTree> newAnnotations = new LinkedList<>(); for (AnnotationTree annotationTree : oldOne.getAnnotations()) { Element el = workingCopy.getTrees().getElement(new TreePath(path, annotationTree)); if(!override.equals(el)) { newAnnotations.add(annotationTree); } } return make.Modifiers(oldOne, newAnnotations); } private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) { final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>(); DeclaredType declaredType = (DeclaredType) sourceType.asType(); for (TypeMirror typeMirror : declaredType.getTypeArguments()) { DeclaredType currentElement = declaredType; deepSearchTypes(currentElement, typeMirror, typeMirror, mappings); } final Types types = workingCopy.getTypes(); final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>(); ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element element = workingCopy.getTrees().getElement(new TreePath(path, node)); if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) { Element typeElement = types.asElement(element.asType()); if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) { TypeParameterElement parameterElement = (TypeParameterElement) typeElement; Element genericElement = parameterElement.getGenericElement(); if (genericElement != member) { // genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen. // Is het parameterElement gebruikt bij het maken van de superclass Tree type; TypeParameterElement target = mappings.get(parameterElement.asType()); if (target != null) { type = make.Type(target.asType()); } else { List<? extends TypeMirror> bounds = parameterElement.getBounds(); if (bounds.isEmpty()) { type = make.Type("Object"); // NOI18N } else { type = make.Type(bounds.get(0)); } } original2Translated.put(node, type); } } } return super.visitIdentifier(node, p); } }; scanner.scan(tree, null); E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated); return result; } private BlockTree updateSuperThisReferences(BlockTree body, final TreePath mpath) { final Map<ExpressionTree, ExpressionTree> original2Translated = new HashMap<ExpressionTree, ExpressionTree>(); final Trees trees = workingCopy.getTrees(); ErrorAwareTreeScanner<Boolean, Void> idScan = new ErrorAwareTreeScanner<Boolean, Void>() { @Override public Boolean visitMemberSelect(MemberSelectTree node, Void nothing) { String isThis = node.getExpression().toString(); if (isThis.equals("super") || isThis.endsWith(".super")) { //NOI18N TreePath currentPath = new TreePath(mpath, node); Element el = trees.getElement(currentPath); if (el != null && el.getEnclosingElement().equals(targetType)) { original2Translated.put(node, make.Identifier(node.getIdentifier())); return Boolean.TRUE; } } return super.visitMemberSelect(node, nothing); } @Override public Boolean reduce(Boolean r1, Boolean r2) { return (r1 == Boolean.TRUE || r2 == Boolean.TRUE); } }; boolean update = idScan.scan(body, null) == Boolean.TRUE; if (update) { body = (BlockTree) workingCopy.getTreeUtilities().translate(body, original2Translated); } return body; } private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) { Types types = workingCopy.getTypes(); List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { DeclaredType type = (DeclaredType) superType; List<? extends TypeMirror> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { TypeMirror typeArgument = typeArguments.get(i); if (something.equals(typeArgument)) { TypeElement asElement = (TypeElement) type.asElement(); mappings.put(orig, asElement.getTypeParameters().get(i)); if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { return true; } if(deepSearchTypes(type, orig, typeArgument, mappings)) { break; } } } if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { mappings.remove(orig); return true; } } return false; } }
apache/netbeans
java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/PullUpTransformer.java
4,850
// genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen.
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.netbeans.modules.refactoring.java.plugins; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.source.util.Trees; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.api.java.source.GeneratorUtilities; import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.TreePathHandle; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.modules.refactoring.java.api.MemberInfo; import org.netbeans.modules.refactoring.java.api.MemberInfo.Group; import org.netbeans.modules.refactoring.java.api.PullUpRefactoring; import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor; import org.netbeans.modules.refactoring.java.spi.ToPhaseException; /** * * @author Jan Becicka * @author Ralph Benjamin Ruijs */ public class PullUpTransformer extends RefactoringVisitor { private MemberInfo<ElementHandle<? extends Element>>[] members; private TypeElement targetType; private TypeElement sourceType; private PullUpRefactoring refactoring; public PullUpTransformer(PullUpRefactoring refactoring) { this.refactoring = refactoring; this.members = refactoring.getMembers(); } @Override public void setWorkingCopy(WorkingCopy copy) throws ToPhaseException { SourceUtils.forceSource(copy, refactoring.getSourceType().getFileObject()); super.setWorkingCopy(copy); this.targetType = refactoring.getTargetType().resolve(copy); this.sourceType = (TypeElement) refactoring.getSourceType().resolveElement(copy); } @Override public Tree visitClass(ClassTree tree, Element p) { Element classElement = workingCopy.getTrees().getElement(getCurrentPath()); GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy); // helper AtomicBoolean classIsAbstract = new AtomicBoolean(classElement.getKind().isInterface()); if (classElement.equals(targetType)) { addMembersToTarget(tree, classIsAbstract, targetType, genUtils); } else if (classElement.equals(sourceType)) { removeMembersFromSource(tree, classIsAbstract); } return super.visitClass(tree, p); } private void addMembersToTarget(ClassTree tree, AtomicBoolean classIsAbstract, TypeElement classElement, GeneratorUtilities genUtils) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { Element member = members[i].getElementHandle().resolve(workingCopy); if(member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } Group group = members[i].getGroup(); if (group == MemberInfo.Group.IMPLEMENTS) { njuClass = make.addClassImplementsClause(njuClass, make.QualIdent(member)); } else { if (members[i].isMakeAbstract()) { if (classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addAbstractMemberToTarget(njuClass, member, classElement, genUtils); } else { if (member.getModifiers().contains(Modifier.ABSTRACT) && classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addMemberToTarget(njuClass, member, classElement, group, genUtils); } } } if (njuClass != tree) { rewrite(tree, njuClass); } } private void removeMembersFromSource(ClassTree tree, AtomicBoolean classIsAbstract) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { if (members[i].getGroup() == MemberInfo.Group.IMPLEMENTS) { for (Tree t : njuClass.getImplementsClause()) { Element currentInterface = workingCopy.getTrees().getElement(TreePath.getPath(getCurrentPath(), t)); if (currentInterface != null && currentInterface.equals(members[i].getElementHandle().resolve(workingCopy))) { njuClass = make.removeClassImplementsClause(njuClass, t); rewrite(tree, njuClass); } } } else { Element current = workingCopy.getTrees().getElement(getCurrentPath()); Element member = members[i].getElementHandle().resolve(workingCopy); if(member != null && member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } if (member != null && member.getEnclosingElement().equals(current)) { if ((classIsAbstract.get() && !member.getModifiers().contains(Modifier.DEFAULT)) || !members[i].isMakeAbstract() || (member.getModifiers().contains(Modifier.ABSTRACT) && targetType.getKind().isInterface())) { // in case of interface always remove pulled method njuClass = make.removeClassMember(njuClass, workingCopy.getTrees().getTree(member)); rewrite(tree, njuClass); } else if (members[i].isMakeAbstract() && member.getModifiers().contains(Modifier.PRIVATE)) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(member); ModifiersTree mods = make.removeModifiersModifier(method.getModifiers(), Modifier.PRIVATE); mods = make.addModifiersModifier(mods, targetType.getKind().isInterface() ? Modifier.PUBLIC : Modifier.PROTECTED); rewrite(method.getModifiers(), mods); } } } } } private ClassTree addAbstractMemberToTarget(ClassTree njuClass, Element methodElm, Element classElement, GeneratorUtilities genUtils) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(methodElm); Set<Modifier> flags = method.getModifiers().getFlags(); Set<Modifier> mod = flags.isEmpty() ? EnumSet.noneOf(Modifier.class) : EnumSet.copyOf(flags); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); // abstract method cannot be default mod.remove(Modifier.DEFAULT); // abstract method cannot be synchronized mod.remove(Modifier.SYNCHRONIZED); if (classElement.getKind().isInterface()) { mod.remove(Modifier.PUBLIC); mod.remove(Modifier.PROTECTED); mod.remove(Modifier.PRIVATE); mod.remove(Modifier.ABSTRACT); } if (mod.contains(Modifier.PRIVATE)) { mod.remove(Modifier.PRIVATE); mod.add(Modifier.PROTECTED); } MethodTree newMethod = make.Method( make.Modifiers(mod), method.getName(), method.getReturnType(), method.getTypeParameters(), method.getParameters(), method.getThrows(), (BlockTree) null, (ExpressionTree) method.getDefaultValue()); newMethod = genUtils.importFQNs(newMethod); method = genUtils.importComments(method, workingCopy.getTrees().getPath(methodElm).getCompilationUnit()); genUtils.copyComments(method, newMethod, false); genUtils.copyComments(method, newMethod, true); njuClass = genUtils.insertClassMember(njuClass, newMethod); return njuClass; } private void makeClassAbstract(ClassTree njuClass) { Set<Modifier> mod = EnumSet.copyOf(njuClass.getModifiers().getFlags()); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); ModifiersTree modifiers = make.Modifiers(mod); rewrite(njuClass.getModifiers(), modifiers); } private ClassTree addMemberToTarget(ClassTree njuClass, Element member, TypeElement classElement, Group group, GeneratorUtilities genUtils) { TreePath mpath = workingCopy.getTrees().getPath(member); Tree memberTree = genUtils.importComments(mpath.getLeaf(), mpath.getCompilationUnit()); memberTree = genUtils.importFQNs(memberTree); memberTree = fixGenericTypes(memberTree, mpath, member); if (member.getModifiers().contains(Modifier.PRIVATE)) { Tree newMemberTree = null; if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); newMemberTree = make.Method( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); } else if (group == Group.FIELD) { VariableTree oldOne = (VariableTree) memberTree; newMemberTree = make.Variable( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getType(), oldOne.getInitializer()); } else if (group == Group.TYPE) { ClassTree oldOne = (ClassTree) memberTree; switch (member.getKind()) { case CLASS: newMemberTree = make.Class( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getExtendsClause(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case INTERFACE: newMemberTree = make.Interface( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case ANNOTATION_TYPE: newMemberTree = make.AnnotationType( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getMembers()); break; case ENUM: newMemberTree = make.Enum( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getImplementsClause(), oldOne.getMembers()); break; } } if (newMemberTree != null) { genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } } else { if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); ExecutableElement overriddenMethod = workingCopy.getElementUtilities().getOverriddenMethod((ExecutableElement) member); MethodTree newMemberTree = make.Method( overriddenMethod != null && workingCopy.getElementUtilities().isMemberOf(overriddenMethod, targetType)? oldOne.getModifiers() : removeAnnotations(workingCopy, make, oldOne.getModifiers(), mpath), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } else { njuClass = genUtils.insertClassMember(njuClass, memberTree); } } return njuClass; } static ModifiersTree removeAnnotations(WorkingCopy workingCopy, TreeMaker make,ModifiersTree oldOne, TreePath path) { TypeElement override = workingCopy.getElements().getTypeElement("java.lang.Override"); if(override == null) { return oldOne; } List<AnnotationTree> newAnnotations = new LinkedList<>(); for (AnnotationTree annotationTree : oldOne.getAnnotations()) { Element el = workingCopy.getTrees().getElement(new TreePath(path, annotationTree)); if(!override.equals(el)) { newAnnotations.add(annotationTree); } } return make.Modifiers(oldOne, newAnnotations); } private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) { final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>(); DeclaredType declaredType = (DeclaredType) sourceType.asType(); for (TypeMirror typeMirror : declaredType.getTypeArguments()) { DeclaredType currentElement = declaredType; deepSearchTypes(currentElement, typeMirror, typeMirror, mappings); } final Types types = workingCopy.getTypes(); final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>(); ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element element = workingCopy.getTrees().getElement(new TreePath(path, node)); if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) { Element typeElement = types.asElement(element.asType()); if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) { TypeParameterElement parameterElement = (TypeParameterElement) typeElement; Element genericElement = parameterElement.getGenericElement(); if (genericElement != member) { // genericElement is<SUF> // Is het parameterElement gebruikt bij het maken van de superclass Tree type; TypeParameterElement target = mappings.get(parameterElement.asType()); if (target != null) { type = make.Type(target.asType()); } else { List<? extends TypeMirror> bounds = parameterElement.getBounds(); if (bounds.isEmpty()) { type = make.Type("Object"); // NOI18N } else { type = make.Type(bounds.get(0)); } } original2Translated.put(node, type); } } } return super.visitIdentifier(node, p); } }; scanner.scan(tree, null); E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated); return result; } private BlockTree updateSuperThisReferences(BlockTree body, final TreePath mpath) { final Map<ExpressionTree, ExpressionTree> original2Translated = new HashMap<ExpressionTree, ExpressionTree>(); final Trees trees = workingCopy.getTrees(); ErrorAwareTreeScanner<Boolean, Void> idScan = new ErrorAwareTreeScanner<Boolean, Void>() { @Override public Boolean visitMemberSelect(MemberSelectTree node, Void nothing) { String isThis = node.getExpression().toString(); if (isThis.equals("super") || isThis.endsWith(".super")) { //NOI18N TreePath currentPath = new TreePath(mpath, node); Element el = trees.getElement(currentPath); if (el != null && el.getEnclosingElement().equals(targetType)) { original2Translated.put(node, make.Identifier(node.getIdentifier())); return Boolean.TRUE; } } return super.visitMemberSelect(node, nothing); } @Override public Boolean reduce(Boolean r1, Boolean r2) { return (r1 == Boolean.TRUE || r2 == Boolean.TRUE); } }; boolean update = idScan.scan(body, null) == Boolean.TRUE; if (update) { body = (BlockTree) workingCopy.getTreeUtilities().translate(body, original2Translated); } return body; } private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) { Types types = workingCopy.getTypes(); List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { DeclaredType type = (DeclaredType) superType; List<? extends TypeMirror> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { TypeMirror typeArgument = typeArguments.get(i); if (something.equals(typeArgument)) { TypeElement asElement = (TypeElement) type.asElement(); mappings.put(orig, asElement.getTypeParameters().get(i)); if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { return true; } if(deepSearchTypes(type, orig, typeArgument, mappings)) { break; } } } if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { mappings.remove(orig); return true; } } return false; } }
752_6
/* * 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.netbeans.modules.refactoring.java.plugins; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.source.util.Trees; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.api.java.source.GeneratorUtilities; import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.TreePathHandle; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.modules.refactoring.java.api.MemberInfo; import org.netbeans.modules.refactoring.java.api.MemberInfo.Group; import org.netbeans.modules.refactoring.java.api.PullUpRefactoring; import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor; import org.netbeans.modules.refactoring.java.spi.ToPhaseException; /** * * @author Jan Becicka * @author Ralph Benjamin Ruijs */ public class PullUpTransformer extends RefactoringVisitor { private MemberInfo<ElementHandle<? extends Element>>[] members; private TypeElement targetType; private TypeElement sourceType; private PullUpRefactoring refactoring; public PullUpTransformer(PullUpRefactoring refactoring) { this.refactoring = refactoring; this.members = refactoring.getMembers(); } @Override public void setWorkingCopy(WorkingCopy copy) throws ToPhaseException { SourceUtils.forceSource(copy, refactoring.getSourceType().getFileObject()); super.setWorkingCopy(copy); this.targetType = refactoring.getTargetType().resolve(copy); this.sourceType = (TypeElement) refactoring.getSourceType().resolveElement(copy); } @Override public Tree visitClass(ClassTree tree, Element p) { Element classElement = workingCopy.getTrees().getElement(getCurrentPath()); GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy); // helper AtomicBoolean classIsAbstract = new AtomicBoolean(classElement.getKind().isInterface()); if (classElement.equals(targetType)) { addMembersToTarget(tree, classIsAbstract, targetType, genUtils); } else if (classElement.equals(sourceType)) { removeMembersFromSource(tree, classIsAbstract); } return super.visitClass(tree, p); } private void addMembersToTarget(ClassTree tree, AtomicBoolean classIsAbstract, TypeElement classElement, GeneratorUtilities genUtils) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { Element member = members[i].getElementHandle().resolve(workingCopy); if(member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } Group group = members[i].getGroup(); if (group == MemberInfo.Group.IMPLEMENTS) { njuClass = make.addClassImplementsClause(njuClass, make.QualIdent(member)); } else { if (members[i].isMakeAbstract()) { if (classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addAbstractMemberToTarget(njuClass, member, classElement, genUtils); } else { if (member.getModifiers().contains(Modifier.ABSTRACT) && classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addMemberToTarget(njuClass, member, classElement, group, genUtils); } } } if (njuClass != tree) { rewrite(tree, njuClass); } } private void removeMembersFromSource(ClassTree tree, AtomicBoolean classIsAbstract) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { if (members[i].getGroup() == MemberInfo.Group.IMPLEMENTS) { for (Tree t : njuClass.getImplementsClause()) { Element currentInterface = workingCopy.getTrees().getElement(TreePath.getPath(getCurrentPath(), t)); if (currentInterface != null && currentInterface.equals(members[i].getElementHandle().resolve(workingCopy))) { njuClass = make.removeClassImplementsClause(njuClass, t); rewrite(tree, njuClass); } } } else { Element current = workingCopy.getTrees().getElement(getCurrentPath()); Element member = members[i].getElementHandle().resolve(workingCopy); if(member != null && member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } if (member != null && member.getEnclosingElement().equals(current)) { if ((classIsAbstract.get() && !member.getModifiers().contains(Modifier.DEFAULT)) || !members[i].isMakeAbstract() || (member.getModifiers().contains(Modifier.ABSTRACT) && targetType.getKind().isInterface())) { // in case of interface always remove pulled method njuClass = make.removeClassMember(njuClass, workingCopy.getTrees().getTree(member)); rewrite(tree, njuClass); } else if (members[i].isMakeAbstract() && member.getModifiers().contains(Modifier.PRIVATE)) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(member); ModifiersTree mods = make.removeModifiersModifier(method.getModifiers(), Modifier.PRIVATE); mods = make.addModifiersModifier(mods, targetType.getKind().isInterface() ? Modifier.PUBLIC : Modifier.PROTECTED); rewrite(method.getModifiers(), mods); } } } } } private ClassTree addAbstractMemberToTarget(ClassTree njuClass, Element methodElm, Element classElement, GeneratorUtilities genUtils) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(methodElm); Set<Modifier> flags = method.getModifiers().getFlags(); Set<Modifier> mod = flags.isEmpty() ? EnumSet.noneOf(Modifier.class) : EnumSet.copyOf(flags); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); // abstract method cannot be default mod.remove(Modifier.DEFAULT); // abstract method cannot be synchronized mod.remove(Modifier.SYNCHRONIZED); if (classElement.getKind().isInterface()) { mod.remove(Modifier.PUBLIC); mod.remove(Modifier.PROTECTED); mod.remove(Modifier.PRIVATE); mod.remove(Modifier.ABSTRACT); } if (mod.contains(Modifier.PRIVATE)) { mod.remove(Modifier.PRIVATE); mod.add(Modifier.PROTECTED); } MethodTree newMethod = make.Method( make.Modifiers(mod), method.getName(), method.getReturnType(), method.getTypeParameters(), method.getParameters(), method.getThrows(), (BlockTree) null, (ExpressionTree) method.getDefaultValue()); newMethod = genUtils.importFQNs(newMethod); method = genUtils.importComments(method, workingCopy.getTrees().getPath(methodElm).getCompilationUnit()); genUtils.copyComments(method, newMethod, false); genUtils.copyComments(method, newMethod, true); njuClass = genUtils.insertClassMember(njuClass, newMethod); return njuClass; } private void makeClassAbstract(ClassTree njuClass) { Set<Modifier> mod = EnumSet.copyOf(njuClass.getModifiers().getFlags()); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); ModifiersTree modifiers = make.Modifiers(mod); rewrite(njuClass.getModifiers(), modifiers); } private ClassTree addMemberToTarget(ClassTree njuClass, Element member, TypeElement classElement, Group group, GeneratorUtilities genUtils) { TreePath mpath = workingCopy.getTrees().getPath(member); Tree memberTree = genUtils.importComments(mpath.getLeaf(), mpath.getCompilationUnit()); memberTree = genUtils.importFQNs(memberTree); memberTree = fixGenericTypes(memberTree, mpath, member); if (member.getModifiers().contains(Modifier.PRIVATE)) { Tree newMemberTree = null; if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); newMemberTree = make.Method( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); } else if (group == Group.FIELD) { VariableTree oldOne = (VariableTree) memberTree; newMemberTree = make.Variable( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getType(), oldOne.getInitializer()); } else if (group == Group.TYPE) { ClassTree oldOne = (ClassTree) memberTree; switch (member.getKind()) { case CLASS: newMemberTree = make.Class( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getExtendsClause(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case INTERFACE: newMemberTree = make.Interface( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case ANNOTATION_TYPE: newMemberTree = make.AnnotationType( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getMembers()); break; case ENUM: newMemberTree = make.Enum( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getImplementsClause(), oldOne.getMembers()); break; } } if (newMemberTree != null) { genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } } else { if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); ExecutableElement overriddenMethod = workingCopy.getElementUtilities().getOverriddenMethod((ExecutableElement) member); MethodTree newMemberTree = make.Method( overriddenMethod != null && workingCopy.getElementUtilities().isMemberOf(overriddenMethod, targetType)? oldOne.getModifiers() : removeAnnotations(workingCopy, make, oldOne.getModifiers(), mpath), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } else { njuClass = genUtils.insertClassMember(njuClass, memberTree); } } return njuClass; } static ModifiersTree removeAnnotations(WorkingCopy workingCopy, TreeMaker make,ModifiersTree oldOne, TreePath path) { TypeElement override = workingCopy.getElements().getTypeElement("java.lang.Override"); if(override == null) { return oldOne; } List<AnnotationTree> newAnnotations = new LinkedList<>(); for (AnnotationTree annotationTree : oldOne.getAnnotations()) { Element el = workingCopy.getTrees().getElement(new TreePath(path, annotationTree)); if(!override.equals(el)) { newAnnotations.add(annotationTree); } } return make.Modifiers(oldOne, newAnnotations); } private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) { final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>(); DeclaredType declaredType = (DeclaredType) sourceType.asType(); for (TypeMirror typeMirror : declaredType.getTypeArguments()) { DeclaredType currentElement = declaredType; deepSearchTypes(currentElement, typeMirror, typeMirror, mappings); } final Types types = workingCopy.getTypes(); final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>(); ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element element = workingCopy.getTrees().getElement(new TreePath(path, node)); if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) { Element typeElement = types.asElement(element.asType()); if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) { TypeParameterElement parameterElement = (TypeParameterElement) typeElement; Element genericElement = parameterElement.getGenericElement(); if (genericElement != member) { // genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen. // Is het parameterElement gebruikt bij het maken van de superclass Tree type; TypeParameterElement target = mappings.get(parameterElement.asType()); if (target != null) { type = make.Type(target.asType()); } else { List<? extends TypeMirror> bounds = parameterElement.getBounds(); if (bounds.isEmpty()) { type = make.Type("Object"); // NOI18N } else { type = make.Type(bounds.get(0)); } } original2Translated.put(node, type); } } } return super.visitIdentifier(node, p); } }; scanner.scan(tree, null); E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated); return result; } private BlockTree updateSuperThisReferences(BlockTree body, final TreePath mpath) { final Map<ExpressionTree, ExpressionTree> original2Translated = new HashMap<ExpressionTree, ExpressionTree>(); final Trees trees = workingCopy.getTrees(); ErrorAwareTreeScanner<Boolean, Void> idScan = new ErrorAwareTreeScanner<Boolean, Void>() { @Override public Boolean visitMemberSelect(MemberSelectTree node, Void nothing) { String isThis = node.getExpression().toString(); if (isThis.equals("super") || isThis.endsWith(".super")) { //NOI18N TreePath currentPath = new TreePath(mpath, node); Element el = trees.getElement(currentPath); if (el != null && el.getEnclosingElement().equals(targetType)) { original2Translated.put(node, make.Identifier(node.getIdentifier())); return Boolean.TRUE; } } return super.visitMemberSelect(node, nothing); } @Override public Boolean reduce(Boolean r1, Boolean r2) { return (r1 == Boolean.TRUE || r2 == Boolean.TRUE); } }; boolean update = idScan.scan(body, null) == Boolean.TRUE; if (update) { body = (BlockTree) workingCopy.getTreeUtilities().translate(body, original2Translated); } return body; } private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) { Types types = workingCopy.getTypes(); List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { DeclaredType type = (DeclaredType) superType; List<? extends TypeMirror> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { TypeMirror typeArgument = typeArguments.get(i); if (something.equals(typeArgument)) { TypeElement asElement = (TypeElement) type.asElement(); mappings.put(orig, asElement.getTypeParameters().get(i)); if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { return true; } if(deepSearchTypes(type, orig, typeArgument, mappings)) { break; } } } if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { mappings.remove(orig); return true; } } return false; } }
apache/netbeans
java/refactoring.java/src/org/netbeans/modules/refactoring/java/plugins/PullUpTransformer.java
4,850
// Is het parameterElement gebruikt bij het maken van de superclass
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.netbeans.modules.refactoring.java.plugins; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import org.netbeans.api.java.source.support.ErrorAwareTreeScanner; import com.sun.source.util.Trees; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.api.java.source.GeneratorUtilities; import org.netbeans.api.java.source.SourceUtils; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.TreePathHandle; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.modules.refactoring.java.api.MemberInfo; import org.netbeans.modules.refactoring.java.api.MemberInfo.Group; import org.netbeans.modules.refactoring.java.api.PullUpRefactoring; import org.netbeans.modules.refactoring.java.spi.RefactoringVisitor; import org.netbeans.modules.refactoring.java.spi.ToPhaseException; /** * * @author Jan Becicka * @author Ralph Benjamin Ruijs */ public class PullUpTransformer extends RefactoringVisitor { private MemberInfo<ElementHandle<? extends Element>>[] members; private TypeElement targetType; private TypeElement sourceType; private PullUpRefactoring refactoring; public PullUpTransformer(PullUpRefactoring refactoring) { this.refactoring = refactoring; this.members = refactoring.getMembers(); } @Override public void setWorkingCopy(WorkingCopy copy) throws ToPhaseException { SourceUtils.forceSource(copy, refactoring.getSourceType().getFileObject()); super.setWorkingCopy(copy); this.targetType = refactoring.getTargetType().resolve(copy); this.sourceType = (TypeElement) refactoring.getSourceType().resolveElement(copy); } @Override public Tree visitClass(ClassTree tree, Element p) { Element classElement = workingCopy.getTrees().getElement(getCurrentPath()); GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy); // helper AtomicBoolean classIsAbstract = new AtomicBoolean(classElement.getKind().isInterface()); if (classElement.equals(targetType)) { addMembersToTarget(tree, classIsAbstract, targetType, genUtils); } else if (classElement.equals(sourceType)) { removeMembersFromSource(tree, classIsAbstract); } return super.visitClass(tree, p); } private void addMembersToTarget(ClassTree tree, AtomicBoolean classIsAbstract, TypeElement classElement, GeneratorUtilities genUtils) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { Element member = members[i].getElementHandle().resolve(workingCopy); if(member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } Group group = members[i].getGroup(); if (group == MemberInfo.Group.IMPLEMENTS) { njuClass = make.addClassImplementsClause(njuClass, make.QualIdent(member)); } else { if (members[i].isMakeAbstract()) { if (classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addAbstractMemberToTarget(njuClass, member, classElement, genUtils); } else { if (member.getModifiers().contains(Modifier.ABSTRACT) && classIsAbstract.compareAndSet(false, true)) { makeClassAbstract(njuClass); } njuClass = addMemberToTarget(njuClass, member, classElement, group, genUtils); } } } if (njuClass != tree) { rewrite(tree, njuClass); } } private void removeMembersFromSource(ClassTree tree, AtomicBoolean classIsAbstract) { ClassTree njuClass = tree; for (int i = 0; i < members.length; i++) { if (members[i].getGroup() == MemberInfo.Group.IMPLEMENTS) { for (Tree t : njuClass.getImplementsClause()) { Element currentInterface = workingCopy.getTrees().getElement(TreePath.getPath(getCurrentPath(), t)); if (currentInterface != null && currentInterface.equals(members[i].getElementHandle().resolve(workingCopy))) { njuClass = make.removeClassImplementsClause(njuClass, t); rewrite(tree, njuClass); } } } else { Element current = workingCopy.getTrees().getElement(getCurrentPath()); Element member = members[i].getElementHandle().resolve(workingCopy); if(member != null && member.getKind() == ElementKind.METHOD) { ExecutableElement method = (ExecutableElement) member; method = (ExecutableElement) workingCopy.getElementUtilities().getImplementationOf(method, sourceType); if(method != null) { member = method; } } if (member != null && member.getEnclosingElement().equals(current)) { if ((classIsAbstract.get() && !member.getModifiers().contains(Modifier.DEFAULT)) || !members[i].isMakeAbstract() || (member.getModifiers().contains(Modifier.ABSTRACT) && targetType.getKind().isInterface())) { // in case of interface always remove pulled method njuClass = make.removeClassMember(njuClass, workingCopy.getTrees().getTree(member)); rewrite(tree, njuClass); } else if (members[i].isMakeAbstract() && member.getModifiers().contains(Modifier.PRIVATE)) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(member); ModifiersTree mods = make.removeModifiersModifier(method.getModifiers(), Modifier.PRIVATE); mods = make.addModifiersModifier(mods, targetType.getKind().isInterface() ? Modifier.PUBLIC : Modifier.PROTECTED); rewrite(method.getModifiers(), mods); } } } } } private ClassTree addAbstractMemberToTarget(ClassTree njuClass, Element methodElm, Element classElement, GeneratorUtilities genUtils) { MethodTree method = (MethodTree) workingCopy.getTrees().getTree(methodElm); Set<Modifier> flags = method.getModifiers().getFlags(); Set<Modifier> mod = flags.isEmpty() ? EnumSet.noneOf(Modifier.class) : EnumSet.copyOf(flags); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); // abstract method cannot be default mod.remove(Modifier.DEFAULT); // abstract method cannot be synchronized mod.remove(Modifier.SYNCHRONIZED); if (classElement.getKind().isInterface()) { mod.remove(Modifier.PUBLIC); mod.remove(Modifier.PROTECTED); mod.remove(Modifier.PRIVATE); mod.remove(Modifier.ABSTRACT); } if (mod.contains(Modifier.PRIVATE)) { mod.remove(Modifier.PRIVATE); mod.add(Modifier.PROTECTED); } MethodTree newMethod = make.Method( make.Modifiers(mod), method.getName(), method.getReturnType(), method.getTypeParameters(), method.getParameters(), method.getThrows(), (BlockTree) null, (ExpressionTree) method.getDefaultValue()); newMethod = genUtils.importFQNs(newMethod); method = genUtils.importComments(method, workingCopy.getTrees().getPath(methodElm).getCompilationUnit()); genUtils.copyComments(method, newMethod, false); genUtils.copyComments(method, newMethod, true); njuClass = genUtils.insertClassMember(njuClass, newMethod); return njuClass; } private void makeClassAbstract(ClassTree njuClass) { Set<Modifier> mod = EnumSet.copyOf(njuClass.getModifiers().getFlags()); mod.add(Modifier.ABSTRACT); mod.remove(Modifier.FINAL); ModifiersTree modifiers = make.Modifiers(mod); rewrite(njuClass.getModifiers(), modifiers); } private ClassTree addMemberToTarget(ClassTree njuClass, Element member, TypeElement classElement, Group group, GeneratorUtilities genUtils) { TreePath mpath = workingCopy.getTrees().getPath(member); Tree memberTree = genUtils.importComments(mpath.getLeaf(), mpath.getCompilationUnit()); memberTree = genUtils.importFQNs(memberTree); memberTree = fixGenericTypes(memberTree, mpath, member); if (member.getModifiers().contains(Modifier.PRIVATE)) { Tree newMemberTree = null; if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); newMemberTree = make.Method( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); } else if (group == Group.FIELD) { VariableTree oldOne = (VariableTree) memberTree; newMemberTree = make.Variable( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getName(), oldOne.getType(), oldOne.getInitializer()); } else if (group == Group.TYPE) { ClassTree oldOne = (ClassTree) memberTree; switch (member.getKind()) { case CLASS: newMemberTree = make.Class( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getExtendsClause(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case INTERFACE: newMemberTree = make.Interface( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getTypeParameters(), oldOne.getImplementsClause(), oldOne.getMembers()); break; case ANNOTATION_TYPE: newMemberTree = make.AnnotationType( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getMembers()); break; case ENUM: newMemberTree = make.Enum( make.addModifiersModifier(make.removeModifiersModifier(oldOne.getModifiers(), Modifier.PRIVATE), Modifier.PROTECTED), oldOne.getSimpleName(), oldOne.getImplementsClause(), oldOne.getMembers()); break; } } if (newMemberTree != null) { genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } } else { if (group == Group.METHOD) { MethodTree oldOne = (MethodTree) memberTree; BlockTree body = updateSuperThisReferences(oldOne.getBody(), mpath); ExecutableElement overriddenMethod = workingCopy.getElementUtilities().getOverriddenMethod((ExecutableElement) member); MethodTree newMemberTree = make.Method( overriddenMethod != null && workingCopy.getElementUtilities().isMemberOf(overriddenMethod, targetType)? oldOne.getModifiers() : removeAnnotations(workingCopy, make, oldOne.getModifiers(), mpath), oldOne.getName(), oldOne.getReturnType(), oldOne.getTypeParameters(), oldOne.getParameters(), oldOne.getThrows(), body, (ExpressionTree) oldOne.getDefaultValue()); genUtils.copyComments(memberTree, newMemberTree, false); genUtils.copyComments(memberTree, newMemberTree, true); njuClass = genUtils.insertClassMember(njuClass, newMemberTree); } else { njuClass = genUtils.insertClassMember(njuClass, memberTree); } } return njuClass; } static ModifiersTree removeAnnotations(WorkingCopy workingCopy, TreeMaker make,ModifiersTree oldOne, TreePath path) { TypeElement override = workingCopy.getElements().getTypeElement("java.lang.Override"); if(override == null) { return oldOne; } List<AnnotationTree> newAnnotations = new LinkedList<>(); for (AnnotationTree annotationTree : oldOne.getAnnotations()) { Element el = workingCopy.getTrees().getElement(new TreePath(path, annotationTree)); if(!override.equals(el)) { newAnnotations.add(annotationTree); } } return make.Modifiers(oldOne, newAnnotations); } private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) { final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>(); DeclaredType declaredType = (DeclaredType) sourceType.asType(); for (TypeMirror typeMirror : declaredType.getTypeArguments()) { DeclaredType currentElement = declaredType; deepSearchTypes(currentElement, typeMirror, typeMirror, mappings); } final Types types = workingCopy.getTypes(); final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>(); ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree node, Void p) { Element element = workingCopy.getTrees().getElement(new TreePath(path, node)); if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) { Element typeElement = types.asElement(element.asType()); if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) { TypeParameterElement parameterElement = (TypeParameterElement) typeElement; Element genericElement = parameterElement.getGenericElement(); if (genericElement != member) { // genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen. // Is het<SUF> Tree type; TypeParameterElement target = mappings.get(parameterElement.asType()); if (target != null) { type = make.Type(target.asType()); } else { List<? extends TypeMirror> bounds = parameterElement.getBounds(); if (bounds.isEmpty()) { type = make.Type("Object"); // NOI18N } else { type = make.Type(bounds.get(0)); } } original2Translated.put(node, type); } } } return super.visitIdentifier(node, p); } }; scanner.scan(tree, null); E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated); return result; } private BlockTree updateSuperThisReferences(BlockTree body, final TreePath mpath) { final Map<ExpressionTree, ExpressionTree> original2Translated = new HashMap<ExpressionTree, ExpressionTree>(); final Trees trees = workingCopy.getTrees(); ErrorAwareTreeScanner<Boolean, Void> idScan = new ErrorAwareTreeScanner<Boolean, Void>() { @Override public Boolean visitMemberSelect(MemberSelectTree node, Void nothing) { String isThis = node.getExpression().toString(); if (isThis.equals("super") || isThis.endsWith(".super")) { //NOI18N TreePath currentPath = new TreePath(mpath, node); Element el = trees.getElement(currentPath); if (el != null && el.getEnclosingElement().equals(targetType)) { original2Translated.put(node, make.Identifier(node.getIdentifier())); return Boolean.TRUE; } } return super.visitMemberSelect(node, nothing); } @Override public Boolean reduce(Boolean r1, Boolean r2) { return (r1 == Boolean.TRUE || r2 == Boolean.TRUE); } }; boolean update = idScan.scan(body, null) == Boolean.TRUE; if (update) { body = (BlockTree) workingCopy.getTreeUtilities().translate(body, original2Translated); } return body; } private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) { Types types = workingCopy.getTypes(); List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement); for (TypeMirror superType : directSupertypes) { DeclaredType type = (DeclaredType) superType; List<? extends TypeMirror> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { TypeMirror typeArgument = typeArguments.get(i); if (something.equals(typeArgument)) { TypeElement asElement = (TypeElement) type.asElement(); mappings.put(orig, asElement.getTypeParameters().get(i)); if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { return true; } if(deepSearchTypes(type, orig, typeArgument, mappings)) { break; } } } if (types.erasure(targetType.asType()).equals(types.erasure(superType))) { mappings.remove(orig); return true; } } return false; } }
764_10
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
seek-for-android/pool
applications/EidForAndroid/src/be/cosic/android/eid/gui/Functions.java
4,569
//TODO : dit niet in een specifieke functie zetten?
line_comment
nl
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO :<SUF> } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
764_21
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
seek-for-android/pool
applications/EidForAndroid/src/be/cosic/android/eid/gui/Functions.java
4,569
//get new pin
line_comment
nl
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new<SUF> intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
764_23
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
seek-for-android/pool
applications/EidForAndroid/src/be/cosic/android/eid/gui/Functions.java
4,569
//get new pin
line_comment
nl
/* * Copyright 2010 Gauthier Van Damme for COSIC * 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 be.cosic.android.eid.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.smartcard.CardException; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import be.cosic.android.eid.exceptions.InvalidPinException; import be.cosic.android.eid.exceptions.InvalidResponse; import be.cosic.android.eid.exceptions.SignatureGenerationException; import be.cosic.android.util.TextUtils; public class Functions extends Activity { private Intent intent; private String old_pin; private String new_pin_1; private String new_pin_2; static final int GET_PIN_FOR_TEST_REQUEST = 0; static final int GET_PIN_FOR_CHANGE_REQUEST_1 = 1; static final int GET_PIN_FOR_CHANGE_REQUEST_2 = 2; static final int GET_PIN_FOR_CHANGE_REQUEST_3 = 3; static final int GET_PIN_FOR_SIGN_REQUEST = 4; static final int GET_RAW_FILE_LOCATION_REQUEST = 5; static final int GET_SIGNED_FILE_LOCATION_REQUEST = 6; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //intent = new Intent().setClass(this, PathQuery.class); } //Note: onResume is also called after onCreate! Do not duplicate code. public void onResume() { super.onResume(); if(MainActivity.own_id == true){ setContentView(R.layout.own_functions); intent = new Intent().setClass(this, PinQuery.class); final Button test_pin = (Button) findViewById(R.id.test_pin); test_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity intent.putExtra("requestCode", GET_PIN_FOR_TEST_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_TEST_REQUEST); //get the pin from the input and check it: see on activity result method } }); final Button change_pin = (Button) findViewById(R.id.change_pin); change_pin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //get old pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_1); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_1); } }); final Button sign = (Button) findViewById(R.id.sign_data); sign.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Get the PIN to enable signing intent.putExtra("requestCode", GET_PIN_FOR_SIGN_REQUEST); Functions.this.startActivityForResult(intent, GET_PIN_FOR_SIGN_REQUEST); } }); final Button authenticate = (Button) findViewById(R.id.authenticate); authenticate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //TODO: need to use SSL for client authentication //also: does eID card implement the PKCS11 standard? used for client authentication //and do we use PKCS11 on both application side (this side) and token side (smart card)? Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; toast = Toast.makeText(context, "Function not implemented yet.", duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); try { setEidData();//TODO : dit niet in een specifieke functie zetten? } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TextView firstnames = (TextView) findViewById(R.id.firstnames); //firstnames.setText("jaja, nu wel ja"); }else { setContentView(R.layout.external_functions); final Button verify = (Button) findViewById(R.id.verify); intent = new Intent().setClass(this, PathQuery.class); verify.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //start new activity Functions.this.startActivityForResult(intent, GET_SIGNED_FILE_LOCATION_REQUEST); //get the pin from the input and check it: see on activity result method } }); } } //Called when a child activity returns. protected void onActivityResult(int requestCode, int resultCode, Intent data) { Context context = getApplicationContext(); int duration = Toast.LENGTH_LONG; Toast toast; switch (requestCode){ //If the return value is a PIN for testing: case GET_PIN_FOR_TEST_REQUEST: if (resultCode == RESULT_OK) { try{ //validate pin MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); CharSequence text = "PIN ok"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_1: if (resultCode == RESULT_OK) { old_pin = data.getStringExtra("PIN"); //get new pin intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_2); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_2); }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_2: if (resultCode == RESULT_OK) { new_pin_1 = data.getStringExtra("PIN"); //get new<SUF> intent.putExtra("requestCode", GET_PIN_FOR_CHANGE_REQUEST_3); Functions.this.startActivityForResult(intent, GET_PIN_FOR_CHANGE_REQUEST_3); //get the pin from the input and change it: see on activity result method }else ; break; //If the return value is a PIN for changing: case GET_PIN_FOR_CHANGE_REQUEST_3: if (resultCode == RESULT_OK) { try{ new_pin_2 = data.getStringExtra("PIN"); if(!new_pin_1.equals(new_pin_2) || new_pin_1.length() != 4){ CharSequence text = "New PIN incorrect"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); break; } //get the pin from the input and change it: see on activity result method MainActivity.belpic.changeThisPin(old_pin, new_pin_1); //clear the pins old_pin = new_pin_1 = new_pin_2 = ""; CharSequence text = "PIN changed"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (InvalidPinException e) { CharSequence text = "Invalid old PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } catch (CardException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else ; break; case GET_SIGNED_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO !!!!!!!!!!!!!!!!! //Check if an extension was added. If not or a false one, correct. //Not everything is checked but other things should be checked by OS // if(!path.endsWith(".crt")) path=path + ".crt"; else if(!path.endsWith(".crt")) throw new UnsupportedEncodingException(); // //We make new directories where necessary // new File(dir).mkdirs(); // // //Now we store the file // //openFileOutput can not contain path separators in its name!!!!!!! // //FileOutputStream fos = openFileOutput(path, Context.MODE_WORLD_READABLE); // FileOutputStream fos = new FileOutputStream(path); // fos.write(currentCert.getEncoded()); // fos.close(); } catch (IOException e) { //TODO e.printStackTrace(); } }else ;//Do nothing break; case GET_PIN_FOR_SIGN_REQUEST: if (resultCode == RESULT_OK) { //try{ //Prepare for signature //MainActivity.belpic.prepareForNonRepudiationSignature(); //MainActivity.belpic.pinValidationEngine(data.getStringExtra("PIN")); //STore PIN old_pin = data.getStringExtra("PIN"); //Ask the path of the file to be signed intent = new Intent().setClass(this, PathQuery.class); Functions.this.startActivityForResult(intent, GET_RAW_FILE_LOCATION_REQUEST); //} }else ;//Do nothing break; case GET_RAW_FILE_LOCATION_REQUEST: if (resultCode == RESULT_OK) { String[] files = data.getStringExtra("path").split(File.separator); String dir = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = dir + File.separator + data.getStringExtra("path"); //Get the directory path for(int i =0;i<(files.length-1);i++){ dir = dir + File.separator + files[i] ; } try { //TODO Make an xml signature??? and imbed reference to document/in document/... //For now, just a signature is created and stored under 'filename.signature' //Encode the file into a byte array byte[] encodedData = TextUtils.getBytesFromFile(path); //Calculate hash MessageDigest hash = MessageDigest.getInstance("SHA-1"); byte[] hashValue = hash.digest(encodedData); //Calculate the signature inside the eID card byte[] signature = MainActivity.belpic.generateNonRepudiationSignature(hashValue, old_pin); //Clear pin: old_pin = ""; //Now we store the signature FileOutputStream fos = new FileOutputStream(path + ".signature"); fos.write(signature); fos.close(); //If everything went fine, let the user know the signature was stored under 'filename_signature.signature' CharSequence text = "Signature saved under: '" + path +".signature'"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (IOException e) { CharSequence text = "IO Exception"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "IOException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { CharSequence text = "NoSuchAlgorithmException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "NoSuchAlgorithmException: " + e.getMessage()); } catch (InvalidResponse e) { CharSequence text = "InvalidResponse"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "InvalidResponse: " + e.getMessage()); } catch (CardException e) { CharSequence text = "CardException"; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "CardException: " + e.getMessage()); } catch (SignatureGenerationException e) { CharSequence text = "SignatureGenerationException: " + e.getMessage(); toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "SignatureGenerationException: " + e.getMessage()); } catch (InvalidPinException e) { CharSequence text = "Invalid PIN: "+ e.getMessage() + " tries left."; toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); Log.e(MainActivity.LOG_TAG, "Exception in PIN validation: " + e.getMessage()); } }else ;//Do nothing break; default: Log.e(MainActivity.LOG_TAG, "Problem in PINquery return result: Invalid return request code."); } } public void setEidData() throws CardException, Exception{ byte[] data = MainActivity.belpic.getCardInfo(); ((TextView) findViewById(R.id.card_data_value)).setText(TextUtils.hexDump(data, data.length - 12, 12)); } }
770_31
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone); if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. * @see #SECONDS_IN_UNIT_S */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
cpf871744029/wsnc
routing/ProphetRouterWithEstimation.java
4,585
// System.out.printf("eezero: %f\t eeone: %f\n", eezero, eeone);
line_comment
nl
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import routing.util.RoutingInfo; import util.Tuple; import core.Connection; import core.DTNHost; import core.Message; import core.Settings; import core.SimClock; /** * Implementation of PRoPHET router as described in * <I>Probabilistic routing in intermittently connected networks</I> by * Anders Lindgren et al. * * * This version tries to estimate a good value of protocol parameters from * a timescale parameter given by the user, and from the encounters the node * sees during simulation. * Refer to Karvo and Ott, <I>Time Scales and Delay-Tolerant Routing * Protocols</I> Chants, 2008 * */ public class ProphetRouterWithEstimation extends ActiveRouter { /** delivery predictability initialization constant*/ public static final double P_INIT = 0.75; /** delivery predictability transitivity scaling constant default value */ public static final double DEFAULT_BETA = 0.25; /** delivery predictability aging constant */ public static final double GAMMA = 0.98; /** default P target */ public static final double DEFAULT_PTARGET = .2; /** Prophet router's setting namespace ({@value})*/ public static final String PROPHET_NS = "ProphetRouterWithEstimation"; /** * Number of seconds in time scale.*/ public static final String TIME_SCALE_S ="timeScale"; /** * Target P_avg * */ public static final String P_AVG_TARGET_S = "targetPavg"; /** * Transitivity scaling constant (beta) -setting id ({@value}). * Default value for setting is {@link #DEFAULT_BETA}. */ public static final String BETA_S = "beta"; /** values of parameter settings */ private double beta; private double gamma; private double pinit; /** value of time scale variable */ private int timescale; private double ptavg; /** delivery predictabilities */ private Map<DTNHost, Double> preds; /** last meeting time with a node */ private Map<DTNHost, Double> meetings; private int nrofSamples; private double meanIET; /** last delivery predictability update (sim)time */ private double lastAgeUpdate; /** * Constructor. Creates a new message router based on the settings in * the given Settings object. * @param s The settings object */ public ProphetRouterWithEstimation(Settings s) { super(s); Settings prophetSettings = new Settings(PROPHET_NS); timescale = prophetSettings.getInt(TIME_SCALE_S); if (prophetSettings.contains(P_AVG_TARGET_S)) { ptavg = prophetSettings.getDouble(P_AVG_TARGET_S); } else { ptavg = DEFAULT_PTARGET; } if (prophetSettings.contains(BETA_S)) { beta = prophetSettings.getDouble(BETA_S); } else { beta = DEFAULT_BETA; } gamma = GAMMA; pinit = P_INIT; initPreds(); initMeetings(); } /** * Copyconstructor. * @param r The router prototype where setting values are copied from */ protected ProphetRouterWithEstimation(ProphetRouterWithEstimation r) { super(r); this.timescale = r.timescale; this.ptavg = r.ptavg; this.beta = r.beta; initPreds(); initMeetings(); } /** * Initializes predictability hash */ private void initPreds() { this.preds = new HashMap<DTNHost, Double>(); } /** * Initializes inter-encounter time estimator */ private void initMeetings() { this.meetings = new HashMap<DTNHost, Double>(); this.meanIET = 0; this.nrofSamples = 0; } @Override public void changedConnection(Connection con) { super.changedConnection(con); if (con.isUp()) { DTNHost otherHost = con.getOtherNode(getHost()); if (updateIET(otherHost)) { updateParams(); } updateDeliveryPredFor(otherHost); updateTransitivePreds(otherHost); } } /** * Updates the interencounter time estimates * @param host */ private boolean updateIET(DTNHost host) { /* First estimate the mean InterEncounter Time */ double currentTime = SimClock.getTime(); if (meetings.containsKey(host)) { double timeDiff = currentTime - meetings.get(host); // System.out.printf("current time: %f\t last time: %f\n",currentTime,meetings.get(host)); nrofSamples++; meanIET = (((double)nrofSamples -1) / (double)nrofSamples) * meanIET + (1 / (double)nrofSamples) * timeDiff; meetings.put(host, currentTime); return true; } else { /* nothing to update */ meetings.put(host,currentTime); return false; } } /** * update PROPHET parameters * */ private void updateParams() { double b; double zeta; double err; boolean cond; int ntarg; double zetadiff; int ozeta; double pstable; double pavg; double ee; double bdiff; int ob; int zcount; boolean bcheck; double pnzero; double pnone; double eezero; double eeone; /* * the estimation algorith does not work for timescales * shorter than the mean IET - so use defaults */ if (meanIET > (double)timescale) { System.out.printf("meanIET %f > %d timescale\n",meanIET,timescale); return; } if (meanIET == 0) { System.out.printf("Mean IET == 0\n"); return; } System.out.printf("prophetfindparams(%d,%f,%f);\n",timescale,ptavg,meanIET); b = 1e-5; zeta = .9; err = 0.005; zetadiff = .1; ozeta = 0; cond = false; ntarg = (int)Math.ceil((double)timescale/(double)meanIET); while (cond == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pavg = (1/(b*meanIET)) * (1-zeta*(1-pstable)) * (1- Math.exp( -b*meanIET)); if (Double.isNaN(pavg)) { pavg = 1; } if (pavg > ptavg) { //System.out.printf("PAVG %f > %f PTAVG\n", pavg,ptavg); if (ozeta == 2) { zetadiff = zetadiff / 2.0; } ozeta = 1; zeta = zeta + zetadiff; if (zeta >= 1) { zeta = 1-zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { if (pavg < ptavg * (1-err)) { // System.out.printf("PAVG %f < %f PTAVG\n", pavg,ptavg); if (ozeta == 1) { zetadiff = zetadiff / 2.0; } ozeta = 2; zeta = zeta-zetadiff; if (zeta <= 0) { zeta = 0 + zetadiff; zetadiff = zetadiff / 2.0; ozeta = 0; } } else { cond = true; } } //System.out.printf("Zeta: %f Zetadiff: %f\n",zeta,zetadiff); ee = 1; bdiff = .1; ob = 0; zcount = 0; // if 100 iterations won't help, lets increase zeta... bcheck = false; while (bcheck == false) { pstable = (1-zeta)/(Math.exp(b*meanIET)-zeta); pnzero = Math.exp(-b*meanIET) * (1-zeta) * ((1-Math.pow(zeta*Math.exp(-b*meanIET),ntarg-1))/ (1-zeta*Math.exp(-b*meanIET))); pnone = Math.pow(zeta*Math.exp(-b*meanIET),ntarg) + pnzero; eezero = Math.abs(pnzero-pstable); eeone = Math.abs(pnone -pstable); ee = Math.max(eezero,eeone); // System.out.printf("Zeta: %f\n", zeta); // System.out.printf("Ptarget: %f \t Pstable: %f\n",ptavg,pstable); // System.out.printf("Pnzero: %f \tPnone: %f\n", pnzero,pnone); // System.out.printf("eezero: %f\t<SUF> if (ee > err) { if (ob == 2) { bdiff = bdiff / 2.0; } ob = 1; b = b+bdiff; } else { if (ee < (err*(1-err))) { if (ob == 1) { bdiff = bdiff / 2.0; } ob = 2; b = b-bdiff; if (b <= 0) { b = 0 + bdiff; bdiff = bdiff / 1.5; ob = 0; } } else { bcheck = true; // System.out.println("******"); } } // System.out.printf("EE: %f B: %f Bdiff: %f\n",ee,b,bdiff); zcount = zcount + 1; if (zcount > 100) { bcheck = true; ozeta = 0; } } } gamma = Math.exp(-b); pinit = 1-zeta; } /** * Updates delivery predictions for a host. * <CODE>P(a,b) = P(a,b)_old + (1 - P(a,b)_old) * P_INIT</CODE> * @param host The host we just met */ private void updateDeliveryPredFor(DTNHost host) { double oldValue = getPredFor(host); double newValue = oldValue + (1 - oldValue) * pinit; preds.put(host, newValue); } /** * Returns the current prediction (P) value for a host or 0 if entry for * the host doesn't exist. * @param host The host to look the P for * @return the current P value */ public double getPredFor(DTNHost host) { ageDeliveryPreds(); // make sure preds are updated before getting if (preds.containsKey(host)) { return preds.get(host); } else { return 0; } } /** * Updates transitive (A->B->C) delivery predictions. * <CODE>P(a,c) = P(a,c)_old + (1 - P(a,c)_old) * P(a,b) * P(b,c) * BETA * </CODE> * @param host The B host who we just met */ private void updateTransitivePreds(DTNHost host) { MessageRouter otherRouter = host.getRouter(); assert otherRouter instanceof ProphetRouterWithEstimation : "PRoPHET only works " + " with other routers of same type"; double pForHost = getPredFor(host); // P(a,b) Map<DTNHost, Double> othersPreds = ((ProphetRouterWithEstimation)otherRouter).getDeliveryPreds(); for (Map.Entry<DTNHost, Double> e : othersPreds.entrySet()) { if (e.getKey() == getHost()) { continue; // don't add yourself } double pOld = getPredFor(e.getKey()); // P(a,c)_old double pNew = pOld + ( 1 - pOld) * pForHost * e.getValue() * beta; preds.put(e.getKey(), pNew); } } /** * Ages all entries in the delivery predictions. * <CODE>P(a,b) = P(a,b)_old * (GAMMA ^ k)</CODE>, where k is number of * time units that have elapsed since the last time the metric was aged. * @see #SECONDS_IN_UNIT_S */ private void ageDeliveryPreds() { double timeDiff = (SimClock.getTime() - this.lastAgeUpdate); if (timeDiff == 0) { return; } double mult = Math.pow(gamma, timeDiff); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { e.setValue(e.getValue()*mult); } this.lastAgeUpdate = SimClock.getTime(); } /** * Returns a map of this router's delivery predictions * @return a map of this router's delivery predictions */ private Map<DTNHost, Double> getDeliveryPreds() { ageDeliveryPreds(); // make sure the aging is done return this.preds; } @Override public void update() { super.update(); if (!canStartTransfer() ||isTransferring()) { return; // nothing to transfer or is currently transferring } // try messages that could be delivered to final recipient if (exchangeDeliverableMessages() != null) { return; } tryOtherMessages(); } /** * Tries to send all other messages to all connected hosts ordered by * their delivery probability * @return The return value of {@link #tryMessagesForConnected(List)} */ private Tuple<Message, Connection> tryOtherMessages() { List<Tuple<Message, Connection>> messages = new ArrayList<Tuple<Message, Connection>>(); Collection<Message> msgCollection = getMessageCollection(); /* for all connected hosts collect all messages that have a higher probability of delivery by the other host */ for (Connection con : getConnections()) { DTNHost other = con.getOtherNode(getHost()); ProphetRouterWithEstimation othRouter = (ProphetRouterWithEstimation)other.getRouter(); if (othRouter.isTransferring()) { continue; // skip hosts that are transferring } for (Message m : msgCollection) { if (othRouter.hasMessage(m.getId())) { continue; // skip messages that the other one has } if (othRouter.getPredFor(m.getTo()) > getPredFor(m.getTo())) { // the other node has higher probability of delivery messages.add(new Tuple<Message, Connection>(m,con)); } } } if (messages.size() == 0) { return null; } // sort the message-connection tuples Collections.sort(messages, new TupleComparator()); return tryMessagesForConnected(messages); // try to send messages } /** * Comparator for Message-Connection-Tuples that orders the tuples by * their delivery probability by the host on the other side of the * connection (GRTRMax) */ private class TupleComparator implements Comparator <Tuple<Message, Connection>> { public int compare(Tuple<Message, Connection> tuple1, Tuple<Message, Connection> tuple2) { // delivery probability of tuple1's message with tuple1's connection double p1 = ((ProphetRouterWithEstimation)tuple1.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple1.getKey().getTo()); // -"- tuple2... double p2 = ((ProphetRouterWithEstimation)tuple2.getValue(). getOtherNode(getHost()).getRouter()).getPredFor( tuple2.getKey().getTo()); // bigger probability should come first if (p2-p1 == 0) { /* equal probabilities -> let queue mode decide */ return compareByQueueMode(tuple1.getKey(), tuple2.getKey()); } else if (p2-p1 < 0) { return -1; } else { return 1; } } } @Override public RoutingInfo getRoutingInfo() { ageDeliveryPreds(); RoutingInfo top = super.getRoutingInfo(); RoutingInfo ri = new RoutingInfo(preds.size() + " delivery prediction(s)"); for (Map.Entry<DTNHost, Double> e : preds.entrySet()) { DTNHost host = e.getKey(); Double value = e.getValue(); ri.addMoreInfo(new RoutingInfo(String.format("%s : %.6f", host, value))); } ri.addMoreInfo(new RoutingInfo(String.format("meanIET: %f\t from %d samples",meanIET,nrofSamples))); ri.addMoreInfo(new RoutingInfo(String.format("current gamma: %f",gamma))); ri.addMoreInfo(new RoutingInfo(String.format("current Pinit: %f",pinit))); top.addMoreInfo(ri); return top; } @Override public MessageRouter replicate() { ProphetRouterWithEstimation r = new ProphetRouterWithEstimation(this); return r; } }
771_13
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import java.io.ByteArrayInputStream; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import jd.PluginWrapper; import jd.http.Browser; import jd.http.URLConnectionAdapter; import jd.nutils.encoding.Encoding; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import jd.plugins.download.DownloadInterface; import org.jdownloader.downloader.hds.HDSDownloader; import org.jdownloader.downloader.hls.HLSDownloader; import org.jdownloader.plugins.components.hls.HlsContainer; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /* * vrt.be network * new content handling --> data-video-src */ @HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactiedecrypted\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporzadecrypted\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" }) public class DeredactieBe extends PluginForHost { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://deredactie.be/"; } private Browser ajax = null; private String finalurl = null; private static enum protocol { HTTP, RTMP, HDS, HLS; } private protocol ptcrl = null; @Override public void correctDownloadLink(DownloadLink link) { link.setUrlDownload(link.getDownloadURL().replace("decrypted.be/", ".be/")); // not sure what this does! -raz link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1")); link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3")); } @Override public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws Exception { this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(downloadLink.getDownloadURL()); // Link offline if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } // Nothing to download if (mediaValue == null || mediaValue.size() == 0) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } finalurl = mediaValue.get("src"); final String filename = mediaValue.get("title"); if (finalurl == null || filename == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } if (finalurl.contains("youtube")) { /* Therefore a decrypter would be needed! */ throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } String ext = getFileNameExtensionFromString(finalurl, ".mp4"); if (ext == null || ext.length() > 5 || ext.equals(".m3u8")) { ext = ".mp4"; } downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "").replace("/", "-") + ext); if (finalurl.contains("vod.stream.vrt.be") && finalurl.endsWith(".m3u8")) { // <div class="video" // data-video-id="2138237_1155250086" // data-video-type="video" // data-video-src="http://vod.stream.vrt.be/deredactie/_definst_/2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4" // data-video-title="Reyers Laat - 3/11/14" // data-video-iphone-server="http://vod.stream.vrt.be/deredactie/_definst_" // data-video-iphone-path="mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/playlist.m3u8" // data-video-rtmp-server="" // data-video-rtmp-path="" // data-video-sitestat-program="reyers_laat_-_31114_id_1-2138237" // data-video-sitestat-playlist="" // data-video-sitestat-site="deredactie-be" // data-video-sitestat-pubdate="1415048604184" // data-video-sitestat-cliptype="FULL_EPISODE" // data-video-sitestat-duration="2564" // data-video-autoplay="true" // data-video-whatsonid="" // data-video-geoblocking="false" // data-video-prerolls-enabled="false" // data-video-preroll-category="senieuws" // data-video-duration="2564000"> try { // Request // URL:http://vod.stream.vrt.be/deredactie/_definst_/mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/manifest.f4m ajaxGetPage(finalurl + "/manifest.f4m"); final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final XPath xPath = XPathFactory.newInstance().newXPath(); Document d = parser.parse(new ByteArrayInputStream(ajax.toString().getBytes("UTF-8"))); NodeList mediaUrls = (NodeList) xPath.evaluate("/manifest/media", d, XPathConstants.NODESET); Node media; for (int j = 0; j < mediaUrls.getLength(); j++) { media = mediaUrls.item(j); // System.out.println(new String(Base64.decode(xPath.evaluate("/manifest/media[" + (j + 1) + "]/metadata", d).trim()))); String temp = getAttByNamedItem(media, "url"); if (temp != null) { finalurl = finalurl + "/" + temp; break; } } ptcrl = protocol.HDS; return AvailableStatus.TRUE; } catch (Throwable t) { t.printStackTrace(); } } if (finalurl.endsWith(".m3u8")) { ptcrl = protocol.HLS; } else { final Browser br2 = br.cloneBrowser(); URLConnectionAdapter con = null; try { con = br2.openGetConnection(finalurl); if (!con.getContentType().contains("html")) { downloadLink.setDownloadSize(con.getLongContentLength()); ptcrl = protocol.HTTP; } else { br2.followConnection(); finalurl = mediaValue.get("rtmp-server"); finalurl = finalurl != null && mediaValue.get("rtmp-path") != null ? finalurl + "@" + mediaValue.get("rtmp-path") : null; if (finalurl == null) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } ptcrl = protocol.RTMP; } } finally { try { con.disconnect(); } catch (Throwable e) { } } } return AvailableStatus.TRUE; } private void ajaxGetPage(final String url) throws Exception { ajax = br.cloneBrowser(); ajax.getHeaders().put("Accept", "*/*"); ajax.getPage(url); } /** * lets try and prevent possible NPE from killing the progress. * * @author raztoki * @param n * @param item * @return */ private String getAttByNamedItem(final Node n, final String item) { final String t = n.getAttributes().getNamedItem(item).getTextContent(); return (t != null ? t.trim() : null); } @Override public void handleFree(DownloadLink downloadLink) throws Exception { requestFileInformation(downloadLink); if (protocol.HDS.equals(ptcrl)) { dl = new HDSDownloader(downloadLink, br, finalurl); dl.startDownload(); return; } else if (protocol.HLS.equals(ptcrl)) { this.br.getPage(finalurl); if (this.br.getHttpConnection().getResponseCode() == 403) { throw new PluginException(LinkStatus.ERROR_FATAL, "This content is GEO-blocked in your country"); } else if (this.br.getHttpConnection().getResponseCode() == 404) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br)); if (hlsbest == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String url_hls = hlsbest.getDownloadurl(); checkFFmpeg(downloadLink, "Download a HLS Stream"); dl = new HLSDownloader(downloadLink, br, url_hls); dl.startDownload(); return; } else if (protocol.RTMP.equals(ptcrl)) { dl = new RTMPDownload(this, downloadLink, finalurl); setupRTMPConnection(dl); ((RTMPDownload) dl).startDownload(); } else { dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalurl, false, 1); if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } dl.startDownload(); } } private void setupRTMPConnection(final DownloadInterface dl) { final jd.network.rtmp.url.RtmpUrlConnection rtmp = ((RTMPDownload) dl).getRtmpConnection(); rtmp.setPlayPath(finalurl.split("@")[1]); rtmp.setUrl(finalurl.split("@")[0]); rtmp.setSwfVfy("http://www.deredactie.be/html/flash/common/player.5.10.swf"); rtmp.setResume(true); rtmp.setRealTime(); } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void reset() { } @Override public void resetPluginGlobals() { } @Override public void resetDownloadlink(DownloadLink link) { if (link != null) { link.removeProperty(HDSDownloader.RESUME_FRAGMENT); } } }
substanc3-dev/jdownloader2
src/jd/plugins/hoster/DeredactieBe.java
3,348
//(www\\.)?deredactiedecrypted\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporzadecrypted\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)" })
line_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import java.io.ByteArrayInputStream; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import jd.PluginWrapper; import jd.http.Browser; import jd.http.URLConnectionAdapter; import jd.nutils.encoding.Encoding; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; import jd.plugins.download.DownloadInterface; import org.jdownloader.downloader.hds.HDSDownloader; import org.jdownloader.downloader.hls.HLSDownloader; import org.jdownloader.plugins.components.hls.HlsContainer; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /* * vrt.be network * new content handling --> data-video-src */ @HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "deredactie.be", "sporza.be" }, urls = { "http://(www\\.)?deredactiedecrypted\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "http://(www\\.)?sporzadecrypted\\.be/(permalink/\\d\\.\\d+|cm/(vrtnieuws|sporza)([^/]+)?/(mediatheek|videozone).+)"<SUF> public class DeredactieBe extends PluginForHost { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://deredactie.be/"; } private Browser ajax = null; private String finalurl = null; private static enum protocol { HTTP, RTMP, HDS, HLS; } private protocol ptcrl = null; @Override public void correctDownloadLink(DownloadLink link) { link.setUrlDownload(link.getDownloadURL().replace("decrypted.be/", ".be/")); // not sure what this does! -raz link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws/mediatheek/[^/]+/[^/]+/[^/]+/([0-9\\.]+)(.+)?", "/permalink/$1")); link.setUrlDownload(link.getDownloadURL().replaceAll("/cm/vrtnieuws([^/]+)?/mediatheek(\\w+)?/([0-9\\.]+)(.+)?", "/permalink/$3")); } @Override public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws Exception { this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(downloadLink.getDownloadURL()); // Link offline if (br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } // Nothing to download if (mediaValue == null || mediaValue.size() == 0) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } finalurl = mediaValue.get("src"); final String filename = mediaValue.get("title"); if (finalurl == null || filename == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } if (finalurl.contains("youtube")) { /* Therefore a decrypter would be needed! */ throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } String ext = getFileNameExtensionFromString(finalurl, ".mp4"); if (ext == null || ext.length() > 5 || ext.equals(".m3u8")) { ext = ".mp4"; } downloadLink.setFinalFileName(Encoding.htmlDecode(filename.trim()).replaceAll("\"", "").replace("/", "-") + ext); if (finalurl.contains("vod.stream.vrt.be") && finalurl.endsWith(".m3u8")) { // <div class="video" // data-video-id="2138237_1155250086" // data-video-type="video" // data-video-src="http://vod.stream.vrt.be/deredactie/_definst_/2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4" // data-video-title="Reyers Laat - 3/11/14" // data-video-iphone-server="http://vod.stream.vrt.be/deredactie/_definst_" // data-video-iphone-path="mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/playlist.m3u8" // data-video-rtmp-server="" // data-video-rtmp-path="" // data-video-sitestat-program="reyers_laat_-_31114_id_1-2138237" // data-video-sitestat-playlist="" // data-video-sitestat-site="deredactie-be" // data-video-sitestat-pubdate="1415048604184" // data-video-sitestat-cliptype="FULL_EPISODE" // data-video-sitestat-duration="2564" // data-video-autoplay="true" // data-video-whatsonid="" // data-video-geoblocking="false" // data-video-prerolls-enabled="false" // data-video-preroll-category="senieuws" // data-video-duration="2564000"> try { // Request // URL:http://vod.stream.vrt.be/deredactie/_definst_/mp4:2014/11/1210141103430708821_Polopoly_16x9_DV25_NGeo.mp4/manifest.f4m ajaxGetPage(finalurl + "/manifest.f4m"); final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final XPath xPath = XPathFactory.newInstance().newXPath(); Document d = parser.parse(new ByteArrayInputStream(ajax.toString().getBytes("UTF-8"))); NodeList mediaUrls = (NodeList) xPath.evaluate("/manifest/media", d, XPathConstants.NODESET); Node media; for (int j = 0; j < mediaUrls.getLength(); j++) { media = mediaUrls.item(j); // System.out.println(new String(Base64.decode(xPath.evaluate("/manifest/media[" + (j + 1) + "]/metadata", d).trim()))); String temp = getAttByNamedItem(media, "url"); if (temp != null) { finalurl = finalurl + "/" + temp; break; } } ptcrl = protocol.HDS; return AvailableStatus.TRUE; } catch (Throwable t) { t.printStackTrace(); } } if (finalurl.endsWith(".m3u8")) { ptcrl = protocol.HLS; } else { final Browser br2 = br.cloneBrowser(); URLConnectionAdapter con = null; try { con = br2.openGetConnection(finalurl); if (!con.getContentType().contains("html")) { downloadLink.setDownloadSize(con.getLongContentLength()); ptcrl = protocol.HTTP; } else { br2.followConnection(); finalurl = mediaValue.get("rtmp-server"); finalurl = finalurl != null && mediaValue.get("rtmp-path") != null ? finalurl + "@" + mediaValue.get("rtmp-path") : null; if (finalurl == null) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } ptcrl = protocol.RTMP; } } finally { try { con.disconnect(); } catch (Throwable e) { } } } return AvailableStatus.TRUE; } private void ajaxGetPage(final String url) throws Exception { ajax = br.cloneBrowser(); ajax.getHeaders().put("Accept", "*/*"); ajax.getPage(url); } /** * lets try and prevent possible NPE from killing the progress. * * @author raztoki * @param n * @param item * @return */ private String getAttByNamedItem(final Node n, final String item) { final String t = n.getAttributes().getNamedItem(item).getTextContent(); return (t != null ? t.trim() : null); } @Override public void handleFree(DownloadLink downloadLink) throws Exception { requestFileInformation(downloadLink); if (protocol.HDS.equals(ptcrl)) { dl = new HDSDownloader(downloadLink, br, finalurl); dl.startDownload(); return; } else if (protocol.HLS.equals(ptcrl)) { this.br.getPage(finalurl); if (this.br.getHttpConnection().getResponseCode() == 403) { throw new PluginException(LinkStatus.ERROR_FATAL, "This content is GEO-blocked in your country"); } else if (this.br.getHttpConnection().getResponseCode() == 404) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } final HlsContainer hlsbest = HlsContainer.findBestVideoByBandwidth(HlsContainer.getHlsQualities(this.br)); if (hlsbest == null) { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } final String url_hls = hlsbest.getDownloadurl(); checkFFmpeg(downloadLink, "Download a HLS Stream"); dl = new HLSDownloader(downloadLink, br, url_hls); dl.startDownload(); return; } else if (protocol.RTMP.equals(ptcrl)) { dl = new RTMPDownload(this, downloadLink, finalurl); setupRTMPConnection(dl); ((RTMPDownload) dl).startDownload(); } else { dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalurl, false, 1); if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } dl.startDownload(); } } private void setupRTMPConnection(final DownloadInterface dl) { final jd.network.rtmp.url.RtmpUrlConnection rtmp = ((RTMPDownload) dl).getRtmpConnection(); rtmp.setPlayPath(finalurl.split("@")[1]); rtmp.setUrl(finalurl.split("@")[0]); rtmp.setSwfVfy("http://www.deredactie.be/html/flash/common/player.5.10.swf"); rtmp.setResume(true); rtmp.setRealTime(); } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void reset() { } @Override public void resetPluginGlobals() { } @Override public void resetDownloadlink(DownloadLink link) { if (link != null) { link.removeProperty(HDSDownloader.RESUME_FRAGMENT); } } }
774_12
/* * Copyright (C) 2016 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.util; import java.io.IOException; import java.security.Principal; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManager; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpSession; import nl.b3p.viewer.config.security.User; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Hibernate; import org.stripesstuff.stripersist.Stripersist; /** * * @author Meine Toonen [email protected] */ public class IPAuthenticationFilter implements Filter { private static final Log log = LogFactory.getLog(IPAuthenticationFilter.class); // The filter configuration object we are associated with. If // this value is null, this filter instance is not currently // configured. private FilterConfig filterConfig = null; private static final String IP_CHECK = IPAuthenticationFilter.class + "_IP_CHECK"; private static final String USER_CHECK = IPAuthenticationFilter.class + "_USER_CHECK"; private static final String TIME_USER_CHECKED = IPAuthenticationFilter.class + "_TIME_USER_CHECKED"; private static final int MAX_TIME_USER_CACHE = 20000; public IPAuthenticationFilter() { } /** * * @param r The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void doFilter(ServletRequest r, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) r; HttpSession session = request.getSession(); if(request.getUserPrincipal() != null){ chain.doFilter(request, response); }else{ User u = null; if((session.getAttribute(IP_CHECK) == null && session.getAttribute(USER_CHECK) == null) || isCacheValid(session)){ String ipAddress = getIp(request); session.setAttribute(IP_CHECK, ipAddress); Stripersist.requestInit(); EntityManager em = Stripersist.getEntityManager(); List<User> users = em.createQuery("from User", User.class).getResultList(); List<User> possibleUsers = new ArrayList<User>(); for (User user : users) { if(checkValidIpAddress(request, user)){ possibleUsers.add(user); } } if(possibleUsers.isEmpty()){ log.debug("No eligible users found for ip"); }else if( possibleUsers.size() == 1){ u = possibleUsers.get(0); u.setAuthenticatedByIp(true); Hibernate.initialize(u.getGroups()); Hibernate.initialize(u.getDetails()); session.setAttribute(IP_CHECK, ipAddress); session.setAttribute(USER_CHECK, u); session.setAttribute(TIME_USER_CHECKED, System.currentTimeMillis()); }else{ log.debug("Too many eligible users found for ip."); } Stripersist.requestComplete(); }else{ u = (User) session.getAttribute(USER_CHECK); } final User user = u; RequestWrapper wrappedRequest = new RequestWrapper((HttpServletRequest) request){ @Override public Principal getUserPrincipal() { if(user != null){ return user; }else{ return super.getUserPrincipal(); } } @Override public String getRemoteUser() { if(user != null){ return user.getName(); }else{ return super.getRemoteUser(); } } @Override public boolean isUserInRole(String role) { if(user != null){ return user.checkRole(role); }else{ return super.isUserInRole(role); } } }; Throwable problem = null; try { chain.doFilter(wrappedRequest, response); } catch (IOException | ServletException t) { log.error("Error processing chain", problem); throw t; } } } /** * Return the filter configuration object for this filter. * @return filter configuration object */ public FilterConfig getFilterConfig() { return (this.filterConfig); } /** * Set the filter configuration object for this filter. * * @param filterConfig The filter configuration object */ public void setFilterConfig(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Destroy method for this filter */ @Override public void destroy() { } /** * Init method for this filter. * * @param filterConfig filter configuration object */ @Override public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Return a String representation of this object. */ @Override public String toString() { if (filterConfig == null) { return ("IPAuthenticationFilter()"); } StringBuilder sb = new StringBuilder("IPAuthenticationFilter("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); } private boolean checkValidIpAddress(HttpServletRequest request, User user) { String remoteAddress = getIp(request); /* remoteaddress controleren tegen ip adressen van user. * Ip ranges mogen ook via een asterisk */ for(String ipAddress: (Set<String>)user.getIps()) { log.debug("Check ip: " + ipAddress + " against: " + remoteAddress); if (ipAddress.contains("*")) { if (isRemoteAddressWithinIpRange(ipAddress, remoteAddress)) { return true; } } if (ipAddress.equalsIgnoreCase(remoteAddress)) { return true; } } log.info("IP address " + remoteAddress + " not allowed for user " + user.getName()); return false; } private String getIp(HttpServletRequest request){ String remoteAddress = request.getRemoteAddr(); String forwardedFor = request.getHeader("X-Forwarded-For"); if (forwardedFor != null) { int endIndex = forwardedFor.contains(",") ? forwardedFor.indexOf(",") : forwardedFor.length(); remoteAddress = forwardedFor.substring(0, endIndex); } return remoteAddress; } /* This function should only be called when ip contains an asterisk. This is the case when someone has given an ip to a user with an asterisk eq. 10.0.0.* */ protected boolean isRemoteAddressWithinIpRange(String ip, String remote) { if (ip == null || remote == null) { return false; } String[] arrIp = ip.split("\\."); String[] arrRemote = remote.split("\\."); if (arrIp == null || arrIp.length < 1 || arrRemote == null || arrRemote.length < 1) { return false; } /* kijken of het niet asteriks gedeelte overeenkomt met hetzelfde gedeelte uit remote address */ for (int i = 0; i < arrIp.length; i++) { if (!arrIp[i].equalsIgnoreCase("*")) { if (!arrIp[i].equalsIgnoreCase(arrRemote[i])) { return false; } } } return true; } private boolean isCacheValid(HttpSession session){ if(session == null){ return true; } if( session.getAttribute(TIME_USER_CHECKED) == null){ return true; } long prev = (long)session.getAttribute(TIME_USER_CHECKED); long now = System.currentTimeMillis(); if(now - prev > MAX_TIME_USER_CACHE){ return true; } return false; } /** * This request wrapper class extends the support class * HttpServletRequestWrapper, which implements all the methods in the * HttpServletRequest interface, as delegations to the wrapped request. You * only need to override the methods that you need to change. You can get * access to the wrapped request using the method getRequest() */ class RequestWrapper extends HttpServletRequestWrapper { public RequestWrapper(HttpServletRequest request) { super(request); } // You might, for example, wish to add a setParameter() method. To do this // you must also override the getParameter, getParameterValues, getParameterMap, // and getParameterNames methods. protected Hashtable localParams = null; public void setParameter(String name, String[] values) { if (localParams == null) { localParams = new Hashtable(); // Copy the parameters from the underlying request. Map wrappedParams = getRequest().getParameterMap(); Set keySet = wrappedParams.keySet(); for (Iterator it = keySet.iterator(); it.hasNext();) { Object key = it.next(); Object value = wrappedParams.get(key); localParams.put(key, value); } } localParams.put(name, values); } @Override public String getParameter(String name) { if (localParams == null) { return getRequest().getParameter(name); } Object val = localParams.get(name); if (val instanceof String) { return (String) val; } if (val instanceof String[]) { String[] values = (String[]) val; return values[0]; } return (val == null ? null : val.toString()); } @Override public String[] getParameterValues(String name) { if (localParams == null) { return getRequest().getParameterValues(name); } return (String[]) localParams.get(name); } @Override public Enumeration getParameterNames() { if (localParams == null) { return getRequest().getParameterNames(); } return localParams.keys(); } @Override public Map getParameterMap() { if (localParams == null) { return getRequest().getParameterMap(); } return localParams; } } }
B3Partners/tailormap
viewer/src/main/java/nl/b3p/viewer/util/IPAuthenticationFilter.java
2,865
/* kijken of het niet asteriks gedeelte overeenkomt met hetzelfde gedeelte uit remote address */
block_comment
nl
/* * Copyright (C) 2016 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.util; import java.io.IOException; import java.security.Principal; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManager; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpSession; import nl.b3p.viewer.config.security.User; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Hibernate; import org.stripesstuff.stripersist.Stripersist; /** * * @author Meine Toonen [email protected] */ public class IPAuthenticationFilter implements Filter { private static final Log log = LogFactory.getLog(IPAuthenticationFilter.class); // The filter configuration object we are associated with. If // this value is null, this filter instance is not currently // configured. private FilterConfig filterConfig = null; private static final String IP_CHECK = IPAuthenticationFilter.class + "_IP_CHECK"; private static final String USER_CHECK = IPAuthenticationFilter.class + "_USER_CHECK"; private static final String TIME_USER_CHECKED = IPAuthenticationFilter.class + "_TIME_USER_CHECKED"; private static final int MAX_TIME_USER_CACHE = 20000; public IPAuthenticationFilter() { } /** * * @param r The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void doFilter(ServletRequest r, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) r; HttpSession session = request.getSession(); if(request.getUserPrincipal() != null){ chain.doFilter(request, response); }else{ User u = null; if((session.getAttribute(IP_CHECK) == null && session.getAttribute(USER_CHECK) == null) || isCacheValid(session)){ String ipAddress = getIp(request); session.setAttribute(IP_CHECK, ipAddress); Stripersist.requestInit(); EntityManager em = Stripersist.getEntityManager(); List<User> users = em.createQuery("from User", User.class).getResultList(); List<User> possibleUsers = new ArrayList<User>(); for (User user : users) { if(checkValidIpAddress(request, user)){ possibleUsers.add(user); } } if(possibleUsers.isEmpty()){ log.debug("No eligible users found for ip"); }else if( possibleUsers.size() == 1){ u = possibleUsers.get(0); u.setAuthenticatedByIp(true); Hibernate.initialize(u.getGroups()); Hibernate.initialize(u.getDetails()); session.setAttribute(IP_CHECK, ipAddress); session.setAttribute(USER_CHECK, u); session.setAttribute(TIME_USER_CHECKED, System.currentTimeMillis()); }else{ log.debug("Too many eligible users found for ip."); } Stripersist.requestComplete(); }else{ u = (User) session.getAttribute(USER_CHECK); } final User user = u; RequestWrapper wrappedRequest = new RequestWrapper((HttpServletRequest) request){ @Override public Principal getUserPrincipal() { if(user != null){ return user; }else{ return super.getUserPrincipal(); } } @Override public String getRemoteUser() { if(user != null){ return user.getName(); }else{ return super.getRemoteUser(); } } @Override public boolean isUserInRole(String role) { if(user != null){ return user.checkRole(role); }else{ return super.isUserInRole(role); } } }; Throwable problem = null; try { chain.doFilter(wrappedRequest, response); } catch (IOException | ServletException t) { log.error("Error processing chain", problem); throw t; } } } /** * Return the filter configuration object for this filter. * @return filter configuration object */ public FilterConfig getFilterConfig() { return (this.filterConfig); } /** * Set the filter configuration object for this filter. * * @param filterConfig The filter configuration object */ public void setFilterConfig(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Destroy method for this filter */ @Override public void destroy() { } /** * Init method for this filter. * * @param filterConfig filter configuration object */ @Override public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Return a String representation of this object. */ @Override public String toString() { if (filterConfig == null) { return ("IPAuthenticationFilter()"); } StringBuilder sb = new StringBuilder("IPAuthenticationFilter("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); } private boolean checkValidIpAddress(HttpServletRequest request, User user) { String remoteAddress = getIp(request); /* remoteaddress controleren tegen ip adressen van user. * Ip ranges mogen ook via een asterisk */ for(String ipAddress: (Set<String>)user.getIps()) { log.debug("Check ip: " + ipAddress + " against: " + remoteAddress); if (ipAddress.contains("*")) { if (isRemoteAddressWithinIpRange(ipAddress, remoteAddress)) { return true; } } if (ipAddress.equalsIgnoreCase(remoteAddress)) { return true; } } log.info("IP address " + remoteAddress + " not allowed for user " + user.getName()); return false; } private String getIp(HttpServletRequest request){ String remoteAddress = request.getRemoteAddr(); String forwardedFor = request.getHeader("X-Forwarded-For"); if (forwardedFor != null) { int endIndex = forwardedFor.contains(",") ? forwardedFor.indexOf(",") : forwardedFor.length(); remoteAddress = forwardedFor.substring(0, endIndex); } return remoteAddress; } /* This function should only be called when ip contains an asterisk. This is the case when someone has given an ip to a user with an asterisk eq. 10.0.0.* */ protected boolean isRemoteAddressWithinIpRange(String ip, String remote) { if (ip == null || remote == null) { return false; } String[] arrIp = ip.split("\\."); String[] arrRemote = remote.split("\\."); if (arrIp == null || arrIp.length < 1 || arrRemote == null || arrRemote.length < 1) { return false; } /* kijken of het<SUF>*/ for (int i = 0; i < arrIp.length; i++) { if (!arrIp[i].equalsIgnoreCase("*")) { if (!arrIp[i].equalsIgnoreCase(arrRemote[i])) { return false; } } } return true; } private boolean isCacheValid(HttpSession session){ if(session == null){ return true; } if( session.getAttribute(TIME_USER_CHECKED) == null){ return true; } long prev = (long)session.getAttribute(TIME_USER_CHECKED); long now = System.currentTimeMillis(); if(now - prev > MAX_TIME_USER_CACHE){ return true; } return false; } /** * This request wrapper class extends the support class * HttpServletRequestWrapper, which implements all the methods in the * HttpServletRequest interface, as delegations to the wrapped request. You * only need to override the methods that you need to change. You can get * access to the wrapped request using the method getRequest() */ class RequestWrapper extends HttpServletRequestWrapper { public RequestWrapper(HttpServletRequest request) { super(request); } // You might, for example, wish to add a setParameter() method. To do this // you must also override the getParameter, getParameterValues, getParameterMap, // and getParameterNames methods. protected Hashtable localParams = null; public void setParameter(String name, String[] values) { if (localParams == null) { localParams = new Hashtable(); // Copy the parameters from the underlying request. Map wrappedParams = getRequest().getParameterMap(); Set keySet = wrappedParams.keySet(); for (Iterator it = keySet.iterator(); it.hasNext();) { Object key = it.next(); Object value = wrappedParams.get(key); localParams.put(key, value); } } localParams.put(name, values); } @Override public String getParameter(String name) { if (localParams == null) { return getRequest().getParameter(name); } Object val = localParams.get(name); if (val instanceof String) { return (String) val; } if (val instanceof String[]) { String[] values = (String[]) val; return values[0]; } return (val == null ? null : val.toString()); } @Override public String[] getParameterValues(String name) { if (localParams == null) { return getRequest().getParameterValues(name); } return (String[]) localParams.get(name); } @Override public Enumeration getParameterNames() { if (localParams == null) { return getRequest().getParameterNames(); } return localParams.keys(); } @Override public Map getParameterMap() { if (localParams == null) { return getRequest().getParameterMap(); } return localParams; } } }
781_12
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.HashMap; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" }) public class DeredactieBe extends PluginForDecrypt { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(parameter); if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { decryptedLinks.add(this.createOfflinelink(parameter)); return decryptedLinks; } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src"); if (finalurl == null) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } return decryptedLinks; } if (finalurl.contains("youtube.com")) { decryptedLinks.add(createDownloadlink(finalurl)); } else { decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/"))); } return decryptedLinks; } /* NO OVERRIDE!! */ public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) { return false; } }
ribonuclecode/jd
src/jd/plugins/decrypter/DeredactieBe.java
899
//([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" })
line_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.HashMap; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.PluginForDecrypt; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+",<SUF> public class DeredactieBe extends PluginForDecrypt { public DeredactieBe(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); this.setBrowserExclusive(); br.setFollowRedirects(true); br.getPage(parameter); if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) { decryptedLinks.add(this.createOfflinelink(parameter)); return decryptedLinks; } HashMap<String, String> mediaValue = new HashMap<String, String>(); for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) { mediaValue.put(s[0], s[1]); } final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src"); if (finalurl == null) { try { decryptedLinks.add(this.createOfflinelink(parameter)); } catch (final Throwable t) { logger.info("Offline Link: " + parameter); } return decryptedLinks; } if (finalurl.contains("youtube.com")) { decryptedLinks.add(createDownloadlink(finalurl)); } else { decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/"))); } return decryptedLinks; } /* NO OVERRIDE!! */ public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) { return false; } }
793_12
//jDownloader - Downloadmanager //Copyright (C) 2012 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import jd.PluginWrapper; import jd.http.Browser; import jd.http.URLConnectionAdapter; import jd.nutils.JDHash; import jd.nutils.encoding.Encoding; import jd.parser.Regex; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; @HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "uitzendinggemist.nl" }, urls = { "http://(www\\.)?uitzendinggemist\\.nl/afleveringen/\\d+" }) public class UitzendinggemistNl extends PluginForHost { private enum Quality { sb, bb, std; } private String clipData; private String finalURL = null; private boolean NEEDSSILVERLIGHT = false; public UitzendinggemistNl(final PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://www.publiekeomroep.nl/disclaimer"; } private String getClipData(final String tag) { return new Regex(clipData, "<" + tag + ">(.*?)</" + tag + ">").getMatch(0); } private void getfinalLink(final String episodeID) throws Exception { /* Diverse urls besorgen. Link ist statisch, kommt aus dem Flashplayer */ final Browser br2 = br.cloneBrowser(); clipData = br2.getPage("http://embed.player.omroep.nl/fl/ug_config.xml"); String nextUrl = getClipData("sessionURL"); if (nextUrl == null) { return; } clipData = br2.getPage(nextUrl); final String[] params = Encoding.Base64Decode(getClipData("key")).split("\\|"); if (params == null || params.length != 4) { return; } nextUrl = "/info/stream/aflevering/" + episodeID + "/" + JDHash.getMD5(episodeID + "|" + params[1]).toUpperCase(); clipData = br2.getPage(nextUrl); if (getClipData("code") != null ? true : false) { return; } final String[] streamUrls = br2.getRegex("(http://[^<>]+)(\n|\r\n)").getColumn(0); if (streamUrls == null || streamUrls.length == 0) { return; } /* sb (low), bb (normal) or std (high) */ String[] Q = new String[2]; for (final String streamUrl : streamUrls) { if (streamUrl.contains("type=http")) { // !mms Q = new Regex(streamUrl, "/([0-9a-z]+_[a-z]+)/").getMatch(0).split("_"); Q[0] = Q[0] == null ? "fallback" : Q[0]; Q[1] = Q[1] == null ? "fallback" : Q[1]; switch (Quality.valueOf(Q[1])) { case sb: if (finalURL == null || !finalURL.contains("_bb/")) { finalURL = streamUrl; } break; case bb: finalURL = streamUrl; break; case std: finalURL = streamUrl; return; default: finalURL = streamUrl; break; } } } } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException { requestFileInformation(downloadLink); if (NEEDSSILVERLIGHT) { throw new PluginException(LinkStatus.ERROR_FATAL, "Can't download MS Silverlight videos!"); } dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalURL, true, 0); if (dl.getConnection().getContentType().contains("text")) { if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } if (dl.getConnection().getContentType().contains("plain")) { final String error = br.toString(); if (error.length() < 100) { throw new PluginException(LinkStatus.ERROR_FATAL, error); } else { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } } } dl.startDownload(); } @Override public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception { setBrowserExclusive(); br.setFollowRedirects(true); br.setCustomCharset("utf-8"); clipData = br.getPage(link.getDownloadURL()); if (br.containsHTML("(>Oeps\\.\\.\\.|Helaas, de opgevraagde pagina bestaat niet|<title>Home \\- Uitzending Gemist</title>)")) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } String filename = getClipData("title").replace("- Uitzending Gemist", ""); if (filename == null) { filename = br.getRegex("<meta content=\"(.*?)\" property=\"og:title\"").getMatch(0); } if (filename == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); filename = Encoding.htmlDecode(filename.trim().replaceAll("(:|,|\\s)", "_")); link.setFinalFileName(filename + ".mp4"); String episodeID = br.getRegex("episodeID=(\\d+)\\&").getMatch(0); if (episodeID == null) { episodeID = br.getRegex("data\\-episode\\-id=\"(\\d+)\"").getMatch(0); } if (episodeID == null) { link.getLinkStatus().setStatusText("Can't download MS Silverlight videos!"); NEEDSSILVERLIGHT = true; return AvailableStatus.TRUE; } /* * Es gibt mehrere Video urls in verschiedenen Qualitäten und Formaten. Methode ermittelt die höchst mögliche Qualität. mms:// Links * werden ignoriert. */ getfinalLink(episodeID); if (finalURL == null) { NEEDSSILVERLIGHT = true; return AvailableStatus.TRUE; } br.setFollowRedirects(true); URLConnectionAdapter con = null; try { con = br.openGetConnection(finalURL); if (!con.getContentType().contains("html")) { link.setDownloadSize(con.getLongContentLength()); } else { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } } finally { try { con.disconnect(); } catch (final Throwable e) { } } return AvailableStatus.TRUE; } @Override public void reset() { } @Override public void resetDownloadlink(final DownloadLink link) { } }
substanc3-dev/jdownloader2
src/jd/plugins/hoster/UitzendinggemistNl.java
2,010
//(www\\.)?uitzendinggemist\\.nl/afleveringen/\\d+" })
line_comment
nl
//jDownloader - Downloadmanager //Copyright (C) 2012 JD-Team [email protected] // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 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 jd.plugins.hoster; import jd.PluginWrapper; import jd.http.Browser; import jd.http.URLConnectionAdapter; import jd.nutils.JDHash; import jd.nutils.encoding.Encoding; import jd.parser.Regex; import jd.plugins.DownloadLink; import jd.plugins.DownloadLink.AvailableStatus; import jd.plugins.HostPlugin; import jd.plugins.LinkStatus; import jd.plugins.PluginException; import jd.plugins.PluginForHost; @HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "uitzendinggemist.nl" }, urls = { "http://(www\\.)?uitzendinggemist\\.nl/afleveringen/\\d+" })<SUF> public class UitzendinggemistNl extends PluginForHost { private enum Quality { sb, bb, std; } private String clipData; private String finalURL = null; private boolean NEEDSSILVERLIGHT = false; public UitzendinggemistNl(final PluginWrapper wrapper) { super(wrapper); } @Override public String getAGBLink() { return "http://www.publiekeomroep.nl/disclaimer"; } private String getClipData(final String tag) { return new Regex(clipData, "<" + tag + ">(.*?)</" + tag + ">").getMatch(0); } private void getfinalLink(final String episodeID) throws Exception { /* Diverse urls besorgen. Link ist statisch, kommt aus dem Flashplayer */ final Browser br2 = br.cloneBrowser(); clipData = br2.getPage("http://embed.player.omroep.nl/fl/ug_config.xml"); String nextUrl = getClipData("sessionURL"); if (nextUrl == null) { return; } clipData = br2.getPage(nextUrl); final String[] params = Encoding.Base64Decode(getClipData("key")).split("\\|"); if (params == null || params.length != 4) { return; } nextUrl = "/info/stream/aflevering/" + episodeID + "/" + JDHash.getMD5(episodeID + "|" + params[1]).toUpperCase(); clipData = br2.getPage(nextUrl); if (getClipData("code") != null ? true : false) { return; } final String[] streamUrls = br2.getRegex("(http://[^<>]+)(\n|\r\n)").getColumn(0); if (streamUrls == null || streamUrls.length == 0) { return; } /* sb (low), bb (normal) or std (high) */ String[] Q = new String[2]; for (final String streamUrl : streamUrls) { if (streamUrl.contains("type=http")) { // !mms Q = new Regex(streamUrl, "/([0-9a-z]+_[a-z]+)/").getMatch(0).split("_"); Q[0] = Q[0] == null ? "fallback" : Q[0]; Q[1] = Q[1] == null ? "fallback" : Q[1]; switch (Quality.valueOf(Q[1])) { case sb: if (finalURL == null || !finalURL.contains("_bb/")) { finalURL = streamUrl; } break; case bb: finalURL = streamUrl; break; case std: finalURL = streamUrl; return; default: finalURL = streamUrl; break; } } } } @Override public int getMaxSimultanFreeDownloadNum() { return -1; } @Override public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException { requestFileInformation(downloadLink); if (NEEDSSILVERLIGHT) { throw new PluginException(LinkStatus.ERROR_FATAL, "Can't download MS Silverlight videos!"); } dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, finalURL, true, 0); if (dl.getConnection().getContentType().contains("text")) { if (dl.getConnection().getContentType().contains("html")) { br.followConnection(); throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } if (dl.getConnection().getContentType().contains("plain")) { final String error = br.toString(); if (error.length() < 100) { throw new PluginException(LinkStatus.ERROR_FATAL, error); } else { throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); } } } dl.startDownload(); } @Override public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception { setBrowserExclusive(); br.setFollowRedirects(true); br.setCustomCharset("utf-8"); clipData = br.getPage(link.getDownloadURL()); if (br.containsHTML("(>Oeps\\.\\.\\.|Helaas, de opgevraagde pagina bestaat niet|<title>Home \\- Uitzending Gemist</title>)")) { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } String filename = getClipData("title").replace("- Uitzending Gemist", ""); if (filename == null) { filename = br.getRegex("<meta content=\"(.*?)\" property=\"og:title\"").getMatch(0); } if (filename == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT); filename = Encoding.htmlDecode(filename.trim().replaceAll("(:|,|\\s)", "_")); link.setFinalFileName(filename + ".mp4"); String episodeID = br.getRegex("episodeID=(\\d+)\\&").getMatch(0); if (episodeID == null) { episodeID = br.getRegex("data\\-episode\\-id=\"(\\d+)\"").getMatch(0); } if (episodeID == null) { link.getLinkStatus().setStatusText("Can't download MS Silverlight videos!"); NEEDSSILVERLIGHT = true; return AvailableStatus.TRUE; } /* * Es gibt mehrere Video urls in verschiedenen Qualitäten und Formaten. Methode ermittelt die höchst mögliche Qualität. mms:// Links * werden ignoriert. */ getfinalLink(episodeID); if (finalURL == null) { NEEDSSILVERLIGHT = true; return AvailableStatus.TRUE; } br.setFollowRedirects(true); URLConnectionAdapter con = null; try { con = br.openGetConnection(finalURL); if (!con.getContentType().contains("html")) { link.setDownloadSize(con.getLongContentLength()); } else { throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND); } } finally { try { con.disconnect(); } catch (final Throwable e) { } } return AvailableStatus.TRUE; } @Override public void reset() { } @Override public void resetDownloadlink(final DownloadLink link) { } }
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,209
// 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(); } }
879_3
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 com.iluwatar.retry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <em>Retry</em> pattern enables applications to handle potentially recoverable failures from * the environment if the business requirements and nature of the failures allow it. By retrying * failed operations on external dependencies, the application may maintain stability and minimize * negative impact on the user experience. * * <p>In our example, we have the {@link BusinessOperation} interface as an abstraction over all * operations that our application performs involving remote systems. The calling code should remain * decoupled from implementations. * * <p>{@link FindCustomer} is a business operation that looks up a customer's record and returns * its ID. Imagine its job is performed by looking up the customer in our local database and * returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link * FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) constructor * parameters} in order to simulate not finding the customer. * * <p>Imagine that, lately, this operation has experienced intermittent failures due to some weird * corruption and/or locking in the data. After retrying a few times the customer is found. The * database is still, however, expected to always be available. While a definitive solution is * found to the problem, our engineers advise us to retry the operation a set number of times with a * set delay between retries, although not too many retries otherwise the end user will be left * waiting for a long time, while delays that are too short will not allow the database to recover * from the load. * * <p>To keep the calling code as decoupled as possible from this workaround, we have implemented * the retry mechanism as a {@link BusinessOperation} named {@link Retry}. * * @author George Aristy ([email protected]) * @see <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Retry pattern * (Microsoft Azure Docs)</a> */ public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static final String NOT_FOUND = "not found"; private static BusinessOperation<String> op; /** * Entry point. * * @param args not used * @throws Exception not expected */ public static void main(String[] args) throws Exception { noErrors(); errorNoRetry(); errorWithRetry(); errorWithRetryExponentialBackoff(); } private static void noErrors() throws Exception { op = new FindCustomer("123"); op.perform(); LOG.info("Sometimes the operation executes with no errors."); } private static void errorNoRetry() throws Exception { op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)); try { op.perform(); } catch (CustomerNotFoundException e) { LOG.info("Yet the operation will throw an error every once in a while."); } } private static void errorWithRetry() throws Exception { final var retry = new Retry<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 3, //3 attempts 100, //100 ms delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } private static void errorWithRetryExponentialBackoff() throws Exception { final var retry = new RetryExponentialBackoff<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 6, //6 attempts 30000, //30 s max delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } }
smedals/java-design-patterns
retry/src/main/java/com/iluwatar/retry/App.java
1,347
//100 ms delay between attempts
line_comment
nl
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 com.iluwatar.retry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <em>Retry</em> pattern enables applications to handle potentially recoverable failures from * the environment if the business requirements and nature of the failures allow it. By retrying * failed operations on external dependencies, the application may maintain stability and minimize * negative impact on the user experience. * * <p>In our example, we have the {@link BusinessOperation} interface as an abstraction over all * operations that our application performs involving remote systems. The calling code should remain * decoupled from implementations. * * <p>{@link FindCustomer} is a business operation that looks up a customer's record and returns * its ID. Imagine its job is performed by looking up the customer in our local database and * returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link * FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) constructor * parameters} in order to simulate not finding the customer. * * <p>Imagine that, lately, this operation has experienced intermittent failures due to some weird * corruption and/or locking in the data. After retrying a few times the customer is found. The * database is still, however, expected to always be available. While a definitive solution is * found to the problem, our engineers advise us to retry the operation a set number of times with a * set delay between retries, although not too many retries otherwise the end user will be left * waiting for a long time, while delays that are too short will not allow the database to recover * from the load. * * <p>To keep the calling code as decoupled as possible from this workaround, we have implemented * the retry mechanism as a {@link BusinessOperation} named {@link Retry}. * * @author George Aristy ([email protected]) * @see <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Retry pattern * (Microsoft Azure Docs)</a> */ public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static final String NOT_FOUND = "not found"; private static BusinessOperation<String> op; /** * Entry point. * * @param args not used * @throws Exception not expected */ public static void main(String[] args) throws Exception { noErrors(); errorNoRetry(); errorWithRetry(); errorWithRetryExponentialBackoff(); } private static void noErrors() throws Exception { op = new FindCustomer("123"); op.perform(); LOG.info("Sometimes the operation executes with no errors."); } private static void errorNoRetry() throws Exception { op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)); try { op.perform(); } catch (CustomerNotFoundException e) { LOG.info("Yet the operation will throw an error every once in a while."); } } private static void errorWithRetry() throws Exception { final var retry = new Retry<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 3, //3 attempts 100, //100 ms<SUF> e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } private static void errorWithRetryExponentialBackoff() throws Exception { final var retry = new RetryExponentialBackoff<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 6, //6 attempts 30000, //30 s max delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } }
879_4
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 com.iluwatar.retry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <em>Retry</em> pattern enables applications to handle potentially recoverable failures from * the environment if the business requirements and nature of the failures allow it. By retrying * failed operations on external dependencies, the application may maintain stability and minimize * negative impact on the user experience. * * <p>In our example, we have the {@link BusinessOperation} interface as an abstraction over all * operations that our application performs involving remote systems. The calling code should remain * decoupled from implementations. * * <p>{@link FindCustomer} is a business operation that looks up a customer's record and returns * its ID. Imagine its job is performed by looking up the customer in our local database and * returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link * FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) constructor * parameters} in order to simulate not finding the customer. * * <p>Imagine that, lately, this operation has experienced intermittent failures due to some weird * corruption and/or locking in the data. After retrying a few times the customer is found. The * database is still, however, expected to always be available. While a definitive solution is * found to the problem, our engineers advise us to retry the operation a set number of times with a * set delay between retries, although not too many retries otherwise the end user will be left * waiting for a long time, while delays that are too short will not allow the database to recover * from the load. * * <p>To keep the calling code as decoupled as possible from this workaround, we have implemented * the retry mechanism as a {@link BusinessOperation} named {@link Retry}. * * @author George Aristy ([email protected]) * @see <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Retry pattern * (Microsoft Azure Docs)</a> */ public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static final String NOT_FOUND = "not found"; private static BusinessOperation<String> op; /** * Entry point. * * @param args not used * @throws Exception not expected */ public static void main(String[] args) throws Exception { noErrors(); errorNoRetry(); errorWithRetry(); errorWithRetryExponentialBackoff(); } private static void noErrors() throws Exception { op = new FindCustomer("123"); op.perform(); LOG.info("Sometimes the operation executes with no errors."); } private static void errorNoRetry() throws Exception { op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)); try { op.perform(); } catch (CustomerNotFoundException e) { LOG.info("Yet the operation will throw an error every once in a while."); } } private static void errorWithRetry() throws Exception { final var retry = new Retry<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 3, //3 attempts 100, //100 ms delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } private static void errorWithRetryExponentialBackoff() throws Exception { final var retry = new RetryExponentialBackoff<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 6, //6 attempts 30000, //30 s max delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } }
smedals/java-design-patterns
retry/src/main/java/com/iluwatar/retry/App.java
1,347
//30 s max delay between attempts
line_comment
nl
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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 com.iluwatar.retry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <em>Retry</em> pattern enables applications to handle potentially recoverable failures from * the environment if the business requirements and nature of the failures allow it. By retrying * failed operations on external dependencies, the application may maintain stability and minimize * negative impact on the user experience. * * <p>In our example, we have the {@link BusinessOperation} interface as an abstraction over all * operations that our application performs involving remote systems. The calling code should remain * decoupled from implementations. * * <p>{@link FindCustomer} is a business operation that looks up a customer's record and returns * its ID. Imagine its job is performed by looking up the customer in our local database and * returning its ID. We can pass {@link CustomerNotFoundException} as one of its {@link * FindCustomer#FindCustomer(java.lang.String, com.iluwatar.retry.BusinessException...) constructor * parameters} in order to simulate not finding the customer. * * <p>Imagine that, lately, this operation has experienced intermittent failures due to some weird * corruption and/or locking in the data. After retrying a few times the customer is found. The * database is still, however, expected to always be available. While a definitive solution is * found to the problem, our engineers advise us to retry the operation a set number of times with a * set delay between retries, although not too many retries otherwise the end user will be left * waiting for a long time, while delays that are too short will not allow the database to recover * from the load. * * <p>To keep the calling code as decoupled as possible from this workaround, we have implemented * the retry mechanism as a {@link BusinessOperation} named {@link Retry}. * * @author George Aristy ([email protected]) * @see <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Retry pattern * (Microsoft Azure Docs)</a> */ public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); public static final String NOT_FOUND = "not found"; private static BusinessOperation<String> op; /** * Entry point. * * @param args not used * @throws Exception not expected */ public static void main(String[] args) throws Exception { noErrors(); errorNoRetry(); errorWithRetry(); errorWithRetryExponentialBackoff(); } private static void noErrors() throws Exception { op = new FindCustomer("123"); op.perform(); LOG.info("Sometimes the operation executes with no errors."); } private static void errorNoRetry() throws Exception { op = new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)); try { op.perform(); } catch (CustomerNotFoundException e) { LOG.info("Yet the operation will throw an error every once in a while."); } } private static void errorWithRetry() throws Exception { final var retry = new Retry<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 3, //3 attempts 100, //100 ms delay between attempts e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } private static void errorWithRetryExponentialBackoff() throws Exception { final var retry = new RetryExponentialBackoff<>( new FindCustomer("123", new CustomerNotFoundException(NOT_FOUND)), 6, //6 attempts 30000, //30 s<SUF> e -> CustomerNotFoundException.class.isAssignableFrom(e.getClass()) ); op = retry; final var customerId = op.perform(); LOG.info(String.format( "However, retrying the operation while ignoring a recoverable error will eventually yield " + "the result %s after a number of attempts %s", customerId, retry.attempts() )); } }
932_2
/** * $Id: EmbedServlet.java,v 1.18 2014/01/31 22:27:07 gaudenz Exp $ * Copyright (c) 2011-2012, JGraph Ltd * * TODO * * We could split the static part and the stencils into two separate requests * in order for multiple graphs in the pages to not load the static part * multiple times. This is only relevant if the embed arguments are different, * in which case there is a problem with parsin the graph model too soon, ie. * before certain stencils become available. * * Easier solution is for the user to move the embed script to after the last * graph in the page and merge the stencil arguments. * * Note: The static part is roundly 105K, the stencils are much smaller in size. * This means if the embed function is widely used, it will make sense to factor * out the static part because only stencils will change between pages. */ package com.mxgraph.online; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.text.StringEscapeUtils; import com.google.appengine.api.utils.SystemProperty; import com.mxgraph.online.Utils.SizeLimitExceededException; /** * Servlet implementation class OpenServlet */ public class EmbedServlet2 extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * */ protected static String SHAPES_PATH = "/shapes"; /** * */ protected static String STENCIL_PATH = "/stencils"; /** * */ protected static String lastModified = null; /** * */ protected HashMap<String, String> stencils = new HashMap<String, String>(); /** * */ protected HashMap<String, String[]> libraries = new HashMap<String, String[]>(); /** * @see HttpServlet#HttpServlet() */ public EmbedServlet2() { if (lastModified == null) { // Uses deployment date as lastModified header String applicationVersion = SystemProperty.applicationVersion.get(); Date uploadDate = new Date(Long .parseLong(applicationVersion .substring(applicationVersion.lastIndexOf(".") + 1)) / (2 << 27) * 1000); DateFormat httpDateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss z", Locale.US); lastModified = httpDateFormat.format(uploadDate); } initLibraries(libraries); } /** * Sets up collection of stencils */ public static void initLibraries(HashMap<String, String[]> libraries) { libraries.put("mockup", new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); libraries.put("arrows2", new String[] { SHAPES_PATH + "/mxArrows.js" }); libraries.put("bpmn", new String[] { SHAPES_PATH + "/bpmn/mxBpmnShape2.js", STENCIL_PATH + "/bpmn.xml" }); libraries.put("er", new String[] { SHAPES_PATH + "/er/mxER.js" }); libraries.put("ios", new String[] { SHAPES_PATH + "/mockup/mxMockupiOS.js" }); libraries.put("rackGeneral", new String[] { SHAPES_PATH + "/rack/mxRack.js", STENCIL_PATH + "/rack/general.xml" }); libraries.put("rackF5", new String[] { STENCIL_PATH + "/rack/f5.xml" }); libraries.put("lean_mapping", new String[] { SHAPES_PATH + "/mxLeanMap.js", STENCIL_PATH + "/lean_mapping.xml" }); libraries.put("basic", new String[] { SHAPES_PATH + "/mxBasic.js", STENCIL_PATH + "/basic.xml" }); libraries.put("ios7icons", new String[] { STENCIL_PATH + "/ios7/icons.xml" }); libraries.put("ios7ui", new String[] { SHAPES_PATH + "/ios7/mxIOS7Ui.js", STENCIL_PATH + "/ios7/misc.xml" }); libraries.put("android", new String[] { SHAPES_PATH + "/mxAndroid.js", STENCIL_PATH + "electrical/transmission" }); libraries.put("electrical/transmission", new String[] { SHAPES_PATH + "/mxElectrical.js", STENCIL_PATH + "/electrical/transmission.xml" }); libraries.put("mockup/buttons", new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); libraries.put("mockup/containers", new String[] { SHAPES_PATH + "/mockup/mxMockupContainers.js" }); libraries.put("mockup/forms", new String[] { SHAPES_PATH + "/mockup/mxMockupForms.js" }); libraries.put("mockup/graphics", new String[] { SHAPES_PATH + "/mockup/mxMockupGraphics.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/markup", new String[] { SHAPES_PATH + "/mockup/mxMockupMarkup.js" }); libraries.put("mockup/misc", new String[] { SHAPES_PATH + "/mockup/mxMockupMisc.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/navigation", new String[] { SHAPES_PATH + "/mockup/mxMockupNavigation.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/text", new String[] { SHAPES_PATH + "/mockup/mxMockupText.js" }); libraries.put("floorplan", new String[] { SHAPES_PATH + "/mxFloorplan.js", STENCIL_PATH + "/floorplan.xml" }); libraries.put("bootstrap", new String[] { SHAPES_PATH + "/mxBootstrap.js", STENCIL_PATH + "/bootstrap.xml" }); libraries.put("gmdl", new String[] { SHAPES_PATH + "/mxGmdl.js", STENCIL_PATH + "/gmdl.xml" }); libraries.put("cabinets", new String[] { SHAPES_PATH + "/mxCabinets.js", STENCIL_PATH + "/cabinets.xml" }); libraries.put("archimate", new String[] { SHAPES_PATH + "/mxArchiMate.js" }); libraries.put("archimate3", new String[] { SHAPES_PATH + "/mxArchiMate3.js" }); libraries.put("sysml", new String[] { SHAPES_PATH + "/mxSysML.js" }); libraries.put("eip", new String[] { SHAPES_PATH + "/mxEip.js", STENCIL_PATH + "/eip.xml" }); libraries.put("networks", new String[] { SHAPES_PATH + "/mxNetworks.js", STENCIL_PATH + "/networks.xml" }); libraries.put("aws3d", new String[] { SHAPES_PATH + "/mxAWS3D.js", STENCIL_PATH + "/aws3d.xml" }); libraries.put("pid2inst", new String[] { SHAPES_PATH + "/pid2/mxPidInstruments.js" }); libraries.put("pid2misc", new String[] { SHAPES_PATH + "/pid2/mxPidMisc.js", STENCIL_PATH + "/pid/misc.xml" }); libraries.put("pid2valves", new String[] { SHAPES_PATH + "/pid2/mxPidValves.js" }); libraries.put("pidFlowSensors", new String[] { STENCIL_PATH + "/pid/flow_sensors.xml" }); libraries.put("emoji", new String[] { SHAPES_PATH + "/emoji/mxEmoji.js" }); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String qs = request.getQueryString(); if (qs != null && qs.equals("stats")) { writeStats(response); } else { // Checks or sets last modified date of delivered content. // Date comparison not needed. Only return 304 if // delivered by this servlet instance. String modSince = request.getHeader("If-Modified-Since"); if (modSince != null && modSince.equals(lastModified) && request.getParameter("fetch") == null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { writeEmbedResponse(request, response); } } } catch (SizeLimitExceededException e) { response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); throw e; } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); throw e; } } public void writeEmbedResponse(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding("UTF-8"); response.setContentType("application/javascript; charset=UTF-8"); response.setHeader("Last-Modified", lastModified); if (request.getParameter("fetch") != null) { response.setHeader("Cache-Control", "no-store"); } OutputStream out = response.getOutputStream(); // Creates XML for stencils PrintWriter writer = new PrintWriter(out); // Writes JavaScript and adds function call with // stylesheet and stencils as arguments writer.println(createEmbedJavaScript(request)); writer.flush(); writer.close(); } public String createEmbedJavaScript(HttpServletRequest request) throws IOException { String sparam = request.getParameter("s"); String dev = request.getParameter("dev"); StringBuffer result = new StringBuffer("["); StringBuffer js = new StringBuffer(""); // Processes each stencil only once HashSet<String> done = new HashSet<String>(); // Processes each lib only once HashSet<String> libsLoaded = new HashSet<String>(); if (sparam != null) { String[] names = sparam.split(";"); for (int i = 0; i < names.length; i++) { if (names[i].indexOf("..") < 0 && !done.contains(names[i]) && names[i].length() > 0) { if (names[i].equals("*")) { js.append(readXmlFile("/js/shapes-14-6-5.min.js", false)); result.append( "'" + readXmlFile("/stencils.xml", true) + "'"); } else { // Makes name canonical names[i] = new File("/" + names[i]).getCanonicalPath().substring(1); // Checks if any JS files are associated with the library // name and injects the JS into the page String[] libs = libraries.get(names[i]); if (libs != null) { for (int j = 0; j < libs.length; j++) { if (!libsLoaded.contains(libs[j])) { String tmp = stencils.get(libs[j]); libsLoaded.add(libs[j]); if (tmp == null) { try { tmp = readXmlFile(libs[j], !libs[j].toLowerCase() .endsWith(".js")); // Cache for later use if (tmp != null) { stencils.put(libs[j], tmp); } } catch (NullPointerException e) { // This seems possible according to access log so ignore stencil } } if (tmp != null) { // TODO: Add JS to Javascript code inline. This had to be done to quickly // add JS-based dynamic loading to the existing embed setup where everything // dynamic is passed via function call, so an indirection via eval must be // used even though the JS could be parsed directly by adding it to JS. if (libs[j].toLowerCase() .endsWith(".js")) { js.append(tmp); } else { if (result.length() > 1) { result.append(","); } result.append("'" + tmp + "'"); } } } } } else { String tmp = stencils.get(names[i]); if (tmp == null) { try { tmp = readXmlFile( "/stencils/" + names[i] + ".xml", true); // Cache for later use if (tmp != null) { stencils.put(names[i], tmp); } } catch (NullPointerException e) { // This seems possible according to access log so ignore stencil } } if (tmp != null) { if (result.length() > 1) { result.append(","); } result.append("'" + tmp + "'"); } } } done.add(names[i]); } } } result.append("]"); // LATER: Detect protocol of request in dev // mode to avoid security errors String proto = "https://"; String setCachedUrls = ""; String[] urls = request.getParameterValues("fetch"); if (urls != null) { HashSet<String> completed = new HashSet<String>(); int sizeLimit = Utils.MAX_SIZE; for (int i = 0; i < urls.length; i++) { // Checks if URL already fetched to avoid duplicates if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i])) { completed.add(urls[i]); URL url = new URL(urls[i]); URLConnection connection = url.openConnection(); ((HttpURLConnection) connection).setInstanceFollowRedirects(false); connection.setRequestProperty("User-Agent", "draw.io"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); String contentLength = connection.getHeaderField("Content-Length"); // If content length is available, use it to enforce maximum size if (contentLength != null && Long.parseLong(contentLength) > sizeLimit) { break; } sizeLimit -= Utils.copyRestricted(connection.getInputStream(), stream); setCachedUrls += "GraphViewer.cachedUrls['" + StringEscapeUtils.escapeEcmaScript(urls[i]) + "'] = decodeURIComponent('" + StringEscapeUtils.escapeEcmaScript( Utils.encodeURIComponent( stream.toString("UTF-8"), Utils.CHARSET_FOR_URL_ENCODING)) + "');"; } } } // Installs a callback to load the stencils after the viewer was injected return "window.onDrawioViewerLoad = function() {" + setCachedUrls + "mxStencilRegistry.parseStencilSets(" + result.toString() + ");" + js + "GraphViewer.processElements(); };" + "var t = document.getElementsByTagName('script');" + "if (t != null && t.length > 0) {" + "var script = document.createElement('script');" + "script.type = 'text/javascript';" + "script.src = '" + proto + ((dev != null && dev.equals("1")) ? "test" : "www") + ".draw.io/js/viewer-static.min.js';" + "t[0].parentNode.appendChild(script);}"; } public void writeStats(HttpServletResponse response) throws IOException { PrintWriter writer = new PrintWriter(response.getOutputStream()); writer.println("<html>"); writer.println("<body>"); writer.println("Deployed: " + lastModified); writer.println("</body>"); writer.println("</html>"); writer.flush(); } public String readXmlFile(String filename, boolean xmlContent) throws IOException { String result = readFile(filename); if (xmlContent) { result = result.replaceAll("'", "\\\\'").replaceAll("\t", "") .replaceAll("\n", ""); } return result; } public String readFile(String filename) throws IOException { InputStream is = getServletContext().getResourceAsStream(filename); return Utils.readInputStream(is); } }
jgraph/drawio
src/main/java/com/mxgraph/online/EmbedServlet2.java
4,299
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
/** * $Id: EmbedServlet.java,v 1.18 2014/01/31 22:27:07 gaudenz Exp $ * Copyright (c) 2011-2012, JGraph Ltd * * TODO * * We could split the static part and the stencils into two separate requests * in order for multiple graphs in the pages to not load the static part * multiple times. This is only relevant if the embed arguments are different, * in which case there is a problem with parsin the graph model too soon, ie. * before certain stencils become available. * * Easier solution is for the user to move the embed script to after the last * graph in the page and merge the stencil arguments. * * Note: The static part is roundly 105K, the stencils are much smaller in size. * This means if the embed function is widely used, it will make sense to factor * out the static part because only stencils will change between pages. */ package com.mxgraph.online; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.text.StringEscapeUtils; import com.google.appengine.api.utils.SystemProperty; import com.mxgraph.online.Utils.SizeLimitExceededException; /** * Servlet implementation class OpenServlet */ public class EmbedServlet2 extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * */ protected static String SHAPES_PATH = "/shapes"; /** * */ protected static String STENCIL_PATH = "/stencils"; /** * */ protected static String lastModified = null; /** * */ protected HashMap<String, String> stencils = new HashMap<String, String>(); /** * */ protected HashMap<String, String[]> libraries = new HashMap<String, String[]>(); /** * @see HttpServlet#HttpServlet() <SUF>*/ public EmbedServlet2() { if (lastModified == null) { // Uses deployment date as lastModified header String applicationVersion = SystemProperty.applicationVersion.get(); Date uploadDate = new Date(Long .parseLong(applicationVersion .substring(applicationVersion.lastIndexOf(".") + 1)) / (2 << 27) * 1000); DateFormat httpDateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss z", Locale.US); lastModified = httpDateFormat.format(uploadDate); } initLibraries(libraries); } /** * Sets up collection of stencils */ public static void initLibraries(HashMap<String, String[]> libraries) { libraries.put("mockup", new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); libraries.put("arrows2", new String[] { SHAPES_PATH + "/mxArrows.js" }); libraries.put("bpmn", new String[] { SHAPES_PATH + "/bpmn/mxBpmnShape2.js", STENCIL_PATH + "/bpmn.xml" }); libraries.put("er", new String[] { SHAPES_PATH + "/er/mxER.js" }); libraries.put("ios", new String[] { SHAPES_PATH + "/mockup/mxMockupiOS.js" }); libraries.put("rackGeneral", new String[] { SHAPES_PATH + "/rack/mxRack.js", STENCIL_PATH + "/rack/general.xml" }); libraries.put("rackF5", new String[] { STENCIL_PATH + "/rack/f5.xml" }); libraries.put("lean_mapping", new String[] { SHAPES_PATH + "/mxLeanMap.js", STENCIL_PATH + "/lean_mapping.xml" }); libraries.put("basic", new String[] { SHAPES_PATH + "/mxBasic.js", STENCIL_PATH + "/basic.xml" }); libraries.put("ios7icons", new String[] { STENCIL_PATH + "/ios7/icons.xml" }); libraries.put("ios7ui", new String[] { SHAPES_PATH + "/ios7/mxIOS7Ui.js", STENCIL_PATH + "/ios7/misc.xml" }); libraries.put("android", new String[] { SHAPES_PATH + "/mxAndroid.js", STENCIL_PATH + "electrical/transmission" }); libraries.put("electrical/transmission", new String[] { SHAPES_PATH + "/mxElectrical.js", STENCIL_PATH + "/electrical/transmission.xml" }); libraries.put("mockup/buttons", new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); libraries.put("mockup/containers", new String[] { SHAPES_PATH + "/mockup/mxMockupContainers.js" }); libraries.put("mockup/forms", new String[] { SHAPES_PATH + "/mockup/mxMockupForms.js" }); libraries.put("mockup/graphics", new String[] { SHAPES_PATH + "/mockup/mxMockupGraphics.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/markup", new String[] { SHAPES_PATH + "/mockup/mxMockupMarkup.js" }); libraries.put("mockup/misc", new String[] { SHAPES_PATH + "/mockup/mxMockupMisc.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/navigation", new String[] { SHAPES_PATH + "/mockup/mxMockupNavigation.js", STENCIL_PATH + "/mockup/misc.xml" }); libraries.put("mockup/text", new String[] { SHAPES_PATH + "/mockup/mxMockupText.js" }); libraries.put("floorplan", new String[] { SHAPES_PATH + "/mxFloorplan.js", STENCIL_PATH + "/floorplan.xml" }); libraries.put("bootstrap", new String[] { SHAPES_PATH + "/mxBootstrap.js", STENCIL_PATH + "/bootstrap.xml" }); libraries.put("gmdl", new String[] { SHAPES_PATH + "/mxGmdl.js", STENCIL_PATH + "/gmdl.xml" }); libraries.put("cabinets", new String[] { SHAPES_PATH + "/mxCabinets.js", STENCIL_PATH + "/cabinets.xml" }); libraries.put("archimate", new String[] { SHAPES_PATH + "/mxArchiMate.js" }); libraries.put("archimate3", new String[] { SHAPES_PATH + "/mxArchiMate3.js" }); libraries.put("sysml", new String[] { SHAPES_PATH + "/mxSysML.js" }); libraries.put("eip", new String[] { SHAPES_PATH + "/mxEip.js", STENCIL_PATH + "/eip.xml" }); libraries.put("networks", new String[] { SHAPES_PATH + "/mxNetworks.js", STENCIL_PATH + "/networks.xml" }); libraries.put("aws3d", new String[] { SHAPES_PATH + "/mxAWS3D.js", STENCIL_PATH + "/aws3d.xml" }); libraries.put("pid2inst", new String[] { SHAPES_PATH + "/pid2/mxPidInstruments.js" }); libraries.put("pid2misc", new String[] { SHAPES_PATH + "/pid2/mxPidMisc.js", STENCIL_PATH + "/pid/misc.xml" }); libraries.put("pid2valves", new String[] { SHAPES_PATH + "/pid2/mxPidValves.js" }); libraries.put("pidFlowSensors", new String[] { STENCIL_PATH + "/pid/flow_sensors.xml" }); libraries.put("emoji", new String[] { SHAPES_PATH + "/emoji/mxEmoji.js" }); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String qs = request.getQueryString(); if (qs != null && qs.equals("stats")) { writeStats(response); } else { // Checks or sets last modified date of delivered content. // Date comparison not needed. Only return 304 if // delivered by this servlet instance. String modSince = request.getHeader("If-Modified-Since"); if (modSince != null && modSince.equals(lastModified) && request.getParameter("fetch") == null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { writeEmbedResponse(request, response); } } } catch (SizeLimitExceededException e) { response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); throw e; } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); throw e; } } public void writeEmbedResponse(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding("UTF-8"); response.setContentType("application/javascript; charset=UTF-8"); response.setHeader("Last-Modified", lastModified); if (request.getParameter("fetch") != null) { response.setHeader("Cache-Control", "no-store"); } OutputStream out = response.getOutputStream(); // Creates XML for stencils PrintWriter writer = new PrintWriter(out); // Writes JavaScript and adds function call with // stylesheet and stencils as arguments writer.println(createEmbedJavaScript(request)); writer.flush(); writer.close(); } public String createEmbedJavaScript(HttpServletRequest request) throws IOException { String sparam = request.getParameter("s"); String dev = request.getParameter("dev"); StringBuffer result = new StringBuffer("["); StringBuffer js = new StringBuffer(""); // Processes each stencil only once HashSet<String> done = new HashSet<String>(); // Processes each lib only once HashSet<String> libsLoaded = new HashSet<String>(); if (sparam != null) { String[] names = sparam.split(";"); for (int i = 0; i < names.length; i++) { if (names[i].indexOf("..") < 0 && !done.contains(names[i]) && names[i].length() > 0) { if (names[i].equals("*")) { js.append(readXmlFile("/js/shapes-14-6-5.min.js", false)); result.append( "'" + readXmlFile("/stencils.xml", true) + "'"); } else { // Makes name canonical names[i] = new File("/" + names[i]).getCanonicalPath().substring(1); // Checks if any JS files are associated with the library // name and injects the JS into the page String[] libs = libraries.get(names[i]); if (libs != null) { for (int j = 0; j < libs.length; j++) { if (!libsLoaded.contains(libs[j])) { String tmp = stencils.get(libs[j]); libsLoaded.add(libs[j]); if (tmp == null) { try { tmp = readXmlFile(libs[j], !libs[j].toLowerCase() .endsWith(".js")); // Cache for later use if (tmp != null) { stencils.put(libs[j], tmp); } } catch (NullPointerException e) { // This seems possible according to access log so ignore stencil } } if (tmp != null) { // TODO: Add JS to Javascript code inline. This had to be done to quickly // add JS-based dynamic loading to the existing embed setup where everything // dynamic is passed via function call, so an indirection via eval must be // used even though the JS could be parsed directly by adding it to JS. if (libs[j].toLowerCase() .endsWith(".js")) { js.append(tmp); } else { if (result.length() > 1) { result.append(","); } result.append("'" + tmp + "'"); } } } } } else { String tmp = stencils.get(names[i]); if (tmp == null) { try { tmp = readXmlFile( "/stencils/" + names[i] + ".xml", true); // Cache for later use if (tmp != null) { stencils.put(names[i], tmp); } } catch (NullPointerException e) { // This seems possible according to access log so ignore stencil } } if (tmp != null) { if (result.length() > 1) { result.append(","); } result.append("'" + tmp + "'"); } } } done.add(names[i]); } } } result.append("]"); // LATER: Detect protocol of request in dev // mode to avoid security errors String proto = "https://"; String setCachedUrls = ""; String[] urls = request.getParameterValues("fetch"); if (urls != null) { HashSet<String> completed = new HashSet<String>(); int sizeLimit = Utils.MAX_SIZE; for (int i = 0; i < urls.length; i++) { // Checks if URL already fetched to avoid duplicates if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i])) { completed.add(urls[i]); URL url = new URL(urls[i]); URLConnection connection = url.openConnection(); ((HttpURLConnection) connection).setInstanceFollowRedirects(false); connection.setRequestProperty("User-Agent", "draw.io"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); String contentLength = connection.getHeaderField("Content-Length"); // If content length is available, use it to enforce maximum size if (contentLength != null && Long.parseLong(contentLength) > sizeLimit) { break; } sizeLimit -= Utils.copyRestricted(connection.getInputStream(), stream); setCachedUrls += "GraphViewer.cachedUrls['" + StringEscapeUtils.escapeEcmaScript(urls[i]) + "'] = decodeURIComponent('" + StringEscapeUtils.escapeEcmaScript( Utils.encodeURIComponent( stream.toString("UTF-8"), Utils.CHARSET_FOR_URL_ENCODING)) + "');"; } } } // Installs a callback to load the stencils after the viewer was injected return "window.onDrawioViewerLoad = function() {" + setCachedUrls + "mxStencilRegistry.parseStencilSets(" + result.toString() + ");" + js + "GraphViewer.processElements(); };" + "var t = document.getElementsByTagName('script');" + "if (t != null && t.length > 0) {" + "var script = document.createElement('script');" + "script.type = 'text/javascript';" + "script.src = '" + proto + ((dev != null && dev.equals("1")) ? "test" : "www") + ".draw.io/js/viewer-static.min.js';" + "t[0].parentNode.appendChild(script);}"; } public void writeStats(HttpServletResponse response) throws IOException { PrintWriter writer = new PrintWriter(response.getOutputStream()); writer.println("<html>"); writer.println("<body>"); writer.println("Deployed: " + lastModified); writer.println("</body>"); writer.println("</html>"); writer.flush(); } public String readXmlFile(String filename, boolean xmlContent) throws IOException { String result = readFile(filename); if (xmlContent) { result = result.replaceAll("'", "\\\\'").replaceAll("\t", "") .replaceAll("\n", ""); } return result; } public String readFile(String filename) throws IOException { InputStream is = getServletContext().getResourceAsStream(filename); return Utils.readInputStream(is); } }
1344_28
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class DecisionTree *****/ class DecisionTree implements Debuggable { public static boolean DISPLAY_INTERNAL_NODES_CLASSIFICATION = false; int name, depth; DecisionTreeNode root; // root of the tree Vector leaves; // list of leaves of the tree (potential growth here) Boost myBoost; int max_size; int split_CV; int number_nodes; // includes leaves double tree_p_t, tree_psi_t, tree_p_t_star; DecisionTree(int nn, Boost bb, int maxs, int split) { name = nn; root = null; myBoost = bb; max_size = maxs; split_CV = split; tree_p_t = tree_psi_t = tree_p_t_star = -1.0; } public String toString() { int i; String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n"; DecisionTreeNode dumn; v += root.display(new HashSet<Integer>()); v += "Leaves:"; Iterator it = leaves.iterator(); while (it.hasNext()) { v += " "; dumn = (DecisionTreeNode) it.next(); v += "#" + dumn.name + dumn.observations_string(); } v += ".\n"; return v; } public static void INSERT_WEIGHT_ORDER(Vector<DecisionTreeNode> all_nodes, DecisionTreeNode nn) { int k; if (all_nodes.size() == 0) all_nodes.addElement(nn); else { k = 0; while ((k < all_nodes.size()) && (nn.train_fold_indexes_in_node.length < all_nodes.elementAt(k).train_fold_indexes_in_node.length)) k++; all_nodes.insertElementAt(nn, k); } } public void grow_heavy_first() { // grows the heaviest grow-able leaf // heavy = wrt the total # examples reaching the node Vector vin, vvv; boolean stop = false; DecisionTreeNode nn, leftnn, rightnn; int i, j, k, l, ibest, pos_left, neg_left, pos_right, neg_right, nsplits = 0; double wpos_left_tempered, wneg_left_tempered, wpos_right_tempered, wneg_right_tempered, t_leaf = myBoost.tempered_t, w_leaf_codensity; double wpos_left_codensity, wneg_left_codensity, wpos_right_codensity, wneg_right_codensity; Vector<DecisionTreeNode> try_leaves = null; // leaves that will be tried to grow Vector candidate_split, dumv; try_leaves = new Vector<>(); for (j = 0; j < leaves.size(); j++) DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, (DecisionTreeNode) leaves.elementAt(j)); do { do { nn = ((DecisionTreeNode) try_leaves.elementAt(0)); candidate_split = nn.bestSplit(t_leaf); if (candidate_split == null) try_leaves.removeElementAt(0); } while ((try_leaves.size() > 0) && (candidate_split == null)); if (candidate_split == null) stop = true; else { vin = candidate_split; nn.is_leaf = false; try_leaves.removeElementAt(0); // nn.node_prediction_from_boosting_weights = nn.node_prediction_from_cardinals = 0.0; nn.feature_node_index = ((Integer) vin.elementAt(2)).intValue(); nn.feature_node_test_index = ((Integer) vin.elementAt(3)).intValue(); pos_left = ((Integer) vin.elementAt(6)).intValue(); neg_left = ((Integer) vin.elementAt(7)).intValue(); pos_right = ((Integer) vin.elementAt(8)).intValue(); neg_right = ((Integer) vin.elementAt(9)).intValue(); wpos_left_tempered = ((Double) vin.elementAt(10)).doubleValue(); wneg_left_tempered = ((Double) vin.elementAt(11)).doubleValue(); wpos_right_tempered = ((Double) vin.elementAt(12)).doubleValue(); wneg_right_tempered = ((Double) vin.elementAt(13)).doubleValue(); wpos_left_codensity = ((Double) vin.elementAt(14)).doubleValue(); wneg_left_codensity = ((Double) vin.elementAt(15)).doubleValue(); wpos_right_codensity = ((Double) vin.elementAt(16)).doubleValue(); wneg_right_codensity = ((Double) vin.elementAt(17)).doubleValue(); number_nodes++; leftnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(4), pos_left, neg_left, wpos_left_tempered, wneg_left_tempered, wpos_left_codensity, wneg_left_codensity); leftnn.compute_prediction(t_leaf); // System.out.println("left_leaf : " + t_leaf + ", wpos_left_codensity = " + // wpos_left_codensity + ", wneg_left_codensity = " + wneg_left_codensity); leftnn.continuous_features_indexes_for_split_copy_from(nn); leftnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.LEFT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, leftnn); number_nodes++; rightnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(5), pos_right, neg_right, wpos_right_tempered, wneg_right_tempered, wpos_right_codensity, wneg_right_codensity); rightnn.compute_prediction(t_leaf); // System.out.println("right_leaf : " + t_leaf + ", wpos_right_codensity = " + // wpos_right_codensity + ", wneg_right_codensity = " + wneg_right_codensity); rightnn.continuous_features_indexes_for_split_copy_from(nn); rightnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.RIGHT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, rightnn); if (nn.depth + 1 > depth) depth = nn.depth + 1; nn.left_child = leftnn; nn.right_child = rightnn; nsplits++; } if (number_nodes >= max_size) stop = true; } while (!stop); // updates leaves in tree leaves = new Vector(); for (j = 0; j < try_leaves.size(); j++) leaves.addElement(try_leaves.elementAt(j)); } public void init(double tt) { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); Vector indexes = new Vector(); Example e; int pos = 0, neg = 0; double wpos_tempered = 0.0, wneg_tempered = 0.0, wpos_codensity = 0.0, wneg_codensity = 0.0, alpha_leaf; for (i = 0; i < ne; i++) { indexes.addElement(new Integer(i)); e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.is_positive_noisy()) { pos++; wpos_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wpos_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } else { neg++; wneg_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wneg_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } } number_nodes = 1; root = new DecisionTreeNode( this, number_nodes, 0, split_CV, indexes, pos, neg, wpos_tempered, wneg_tempered, wpos_codensity, wneg_codensity); root.init_continuous_features_indexes_for_split(); depth = 0; // System.out.println("tt = " + tt + ", root_leaf : " + root + ", wpos_codensity = " + // wpos_codensity + ", wneg_codensity = " + wneg_codensity); root.compute_prediction(myBoost.tempered_t); leaves = new Vector(); leaves.addElement(root); } public DecisionTreeNode get_leaf(Example ee) { // returns the leaf reached by the example DecisionTreeNode nn = root; Feature f; while (!nn.is_leaf) { f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return nn; } public DecisionTreeNode get_leaf_MonotonicTreeGraph(Example ee) { // returns the monotonic node reached by the example // (builds a strictly monotonic path of nodes to a leaf, used the last one in the path; this is // a prediction node in the corresponding MonotonicTreeGraph) DecisionTreeNode nn = root; double best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); DecisionTreeNode ret = root; Feature f; while (!nn.is_leaf) { if (Math.abs(nn.node_prediction_from_boosting_weights) > best_prediction) { best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); ret = nn; } f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return ret; } public double leveraging_mu() { if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) return leveraging_mu_tempered_loss(); else if (myBoost.name.equals(Boost.KEY_NAME_LOG_LOSS)) return leveraging_mu_log_loss(); else Dataset.perror("DecisionTree.class :: no loss " + myBoost.name); return -1.0; } public double leveraging_mu_log_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); double rho_j = 0.0, max_absolute_pred = -1.0, output_e, tot_weight = 0.0, mu_j; Example e; for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); output_e = output_boosting(e); if ((i == 0) || (Math.abs(output_e) > max_absolute_pred)) max_absolute_pred = Math.abs(output_e); rho_j += (e.current_boosting_weight * output_e * e.noisy_normalized_class); tot_weight += e.current_boosting_weight; } rho_j /= (tot_weight * max_absolute_pred); tree_p_t = (1.0 + rho_j) / 2.0; tree_psi_t = Math.log((1.0 + rho_j) / (1.0 - rho_j)); tree_p_t_star = 1.0 / (1.0 + Math.exp(-max_absolute_pred)); if (tree_psi_t < 0.0) Dataset.perror("DecisionTree.class :: negative value tree_psi_t = " + tree_psi_t); // if ( (rho_j >= 1.0) || (rho_j <= -1.0) ) // Dataset.perror("DecisionTree.class :: impossible value rho_j = " + rho_j); REMOVE mu_j = (Math.log((1.0 + rho_j) / (1.0 - rho_j))) / max_absolute_pred; return mu_j; } public double leveraging_mu_tempered_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV), maxr, nbpos = 0, nbnull = 0; double r_j = 0.0, epsilon_j = 0.0, rho_j = 0.0, ww, mu_j, rat; Example e; // computes r_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight < 0.0) Dataset.perror("DecisionTree.class :: example has negative weight"); if (e.current_boosting_weight > 0.0) { if (myBoost.tempered_t != 1.0) rat = Math.abs(unweighted_edge_training(e)) / Math.pow(e.current_boosting_weight, 1.0 - myBoost.tempered_t); else rat = Math.abs(unweighted_edge_training(e)); if ((nbpos == 0) || (rat > r_j)) r_j = rat; nbpos++; } } if (r_j == 0.0) // h = 0 => mu = 0 return 0.0; // computes epsilon_j, see paper if (myBoost.tempered_t != 1.0) { for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight == 0.0) { rat = Math.abs(unweighted_edge_training(e)) / r_j; if ((nbnull == 0) || (rat > epsilon_j)) { epsilon_j = rat; } nbnull++; } } if (nbnull > 0) epsilon_j = Math.pow(epsilon_j, 1.0 / (1.0 - myBoost.tempered_t)); } // computes rho_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); ww = (e.current_boosting_weight > 0.0) ? e.current_boosting_weight : epsilon_j; rho_j += ww * unweighted_edge_training(e); } rho_j /= ((1.0 + (((double) nbnull) * Math.pow(epsilon_j, 2.0 - myBoost.tempered_t))) * r_j); if ((rho_j > 1.0) || (rho_j < -1.0)) Dataset.perror("DecisionTree.class :: rho_j = " + rho_j + " not in [-1,1]"); // System.out.println("BEFORE " + myBoost.tempered_t + ", rho = " + rho_j); mu_j = -Statistics.TEMPERED_LOG( (1.0 - rho_j) / Statistics.Q_MEAN(1.0 - rho_j, 1.0 + rho_j, 1.0 - myBoost.tempered_t), myBoost.tempered_t); // System.out.println("AFTER " + myBoost.tempered_t + ", mu = " + mu_j); if ((Double.isNaN(mu_j)) || (Double.isInfinite(mu_j))) { if (rho_j > 0.0) mu_j = Boost.MAX_PRED_VALUE; else if (rho_j < 0.0) mu_j = -Boost.MAX_PRED_VALUE; else Dataset.perror("DecisionTree.class :: inconsistency in the computation of rho_j"); TemperedBoostException.ADD(TemperedBoostException.NUMERICAL_ISSUES_INFINITE_MU); } mu_j /= r_j; return mu_j; } public double leveraging_alpha(double mu, Vector<Double> allzs) { if ((myBoost.tempered_t == 1.0) || (!myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))) return mu; double al = Math.pow( (double) myBoost.myDomain.myDS.train_size(split_CV), 1.0 - Statistics.STAR(myBoost.tempered_t)); int i; if (name > 0) { for (i = 0; i < name; i++) al *= Math.pow(allzs.elementAt(i).doubleValue(), 1.0 - myBoost.tempered_t); } al *= mu; return al; } public double output_boosting(Example ee) { DecisionTreeNode nn = get_leaf(ee); // if (ee.domain_id == 1){ // System.out.println("DT [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput(); return (nn.node_prediction_from_boosting_weights); } public double output_boosting_MonotonicTreeGraph(Example ee) { DecisionTreeNode nn = get_leaf_MonotonicTreeGraph(ee); // if (ee.domain_id == 1){ // System.out.println("MTG [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput_MonotonicTreeGraph(); return (nn.node_prediction_from_boosting_weights); } public double unweighted_edge_training(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting(ee)) * (ee.noisy_normalized_class)); } public double unweighted_edge_training_MonotonicTreeGraph(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting_MonotonicTreeGraph(ee)) * (ee.noisy_normalized_class)); } // safe checks methods public void check() { int i, j, ne = myBoost.myDomain.myDS.train_size(split_CV); DecisionTreeNode leaf1, leaf2; Example ee; for (i = 0; i < leaves.size(); i++) { leaf1 = (DecisionTreeNode) leaves.elementAt(i); for (j = 0; j < leaf1.train_fold_indexes_in_node.length; j++) { ee = myBoost.myDomain.myDS.train_example(split_CV, leaf1.train_fold_indexes_in_node[j]); leaf2 = get_leaf(ee); if (leaf1.name != leaf2.name) { Dataset.perror( "DecisionTree.class :: Example " + ee + " reaches leaf #" + leaf2 + " but is recorded for leaf #" + leaf1); } } } } }
google-research/google-research
tempered_boosting/DecisionTree.java
5,313
// if (ee.domain_id == 1){
line_comment
nl
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class DecisionTree *****/ class DecisionTree implements Debuggable { public static boolean DISPLAY_INTERNAL_NODES_CLASSIFICATION = false; int name, depth; DecisionTreeNode root; // root of the tree Vector leaves; // list of leaves of the tree (potential growth here) Boost myBoost; int max_size; int split_CV; int number_nodes; // includes leaves double tree_p_t, tree_psi_t, tree_p_t_star; DecisionTree(int nn, Boost bb, int maxs, int split) { name = nn; root = null; myBoost = bb; max_size = maxs; split_CV = split; tree_p_t = tree_psi_t = tree_p_t_star = -1.0; } public String toString() { int i; String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n"; DecisionTreeNode dumn; v += root.display(new HashSet<Integer>()); v += "Leaves:"; Iterator it = leaves.iterator(); while (it.hasNext()) { v += " "; dumn = (DecisionTreeNode) it.next(); v += "#" + dumn.name + dumn.observations_string(); } v += ".\n"; return v; } public static void INSERT_WEIGHT_ORDER(Vector<DecisionTreeNode> all_nodes, DecisionTreeNode nn) { int k; if (all_nodes.size() == 0) all_nodes.addElement(nn); else { k = 0; while ((k < all_nodes.size()) && (nn.train_fold_indexes_in_node.length < all_nodes.elementAt(k).train_fold_indexes_in_node.length)) k++; all_nodes.insertElementAt(nn, k); } } public void grow_heavy_first() { // grows the heaviest grow-able leaf // heavy = wrt the total # examples reaching the node Vector vin, vvv; boolean stop = false; DecisionTreeNode nn, leftnn, rightnn; int i, j, k, l, ibest, pos_left, neg_left, pos_right, neg_right, nsplits = 0; double wpos_left_tempered, wneg_left_tempered, wpos_right_tempered, wneg_right_tempered, t_leaf = myBoost.tempered_t, w_leaf_codensity; double wpos_left_codensity, wneg_left_codensity, wpos_right_codensity, wneg_right_codensity; Vector<DecisionTreeNode> try_leaves = null; // leaves that will be tried to grow Vector candidate_split, dumv; try_leaves = new Vector<>(); for (j = 0; j < leaves.size(); j++) DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, (DecisionTreeNode) leaves.elementAt(j)); do { do { nn = ((DecisionTreeNode) try_leaves.elementAt(0)); candidate_split = nn.bestSplit(t_leaf); if (candidate_split == null) try_leaves.removeElementAt(0); } while ((try_leaves.size() > 0) && (candidate_split == null)); if (candidate_split == null) stop = true; else { vin = candidate_split; nn.is_leaf = false; try_leaves.removeElementAt(0); // nn.node_prediction_from_boosting_weights = nn.node_prediction_from_cardinals = 0.0; nn.feature_node_index = ((Integer) vin.elementAt(2)).intValue(); nn.feature_node_test_index = ((Integer) vin.elementAt(3)).intValue(); pos_left = ((Integer) vin.elementAt(6)).intValue(); neg_left = ((Integer) vin.elementAt(7)).intValue(); pos_right = ((Integer) vin.elementAt(8)).intValue(); neg_right = ((Integer) vin.elementAt(9)).intValue(); wpos_left_tempered = ((Double) vin.elementAt(10)).doubleValue(); wneg_left_tempered = ((Double) vin.elementAt(11)).doubleValue(); wpos_right_tempered = ((Double) vin.elementAt(12)).doubleValue(); wneg_right_tempered = ((Double) vin.elementAt(13)).doubleValue(); wpos_left_codensity = ((Double) vin.elementAt(14)).doubleValue(); wneg_left_codensity = ((Double) vin.elementAt(15)).doubleValue(); wpos_right_codensity = ((Double) vin.elementAt(16)).doubleValue(); wneg_right_codensity = ((Double) vin.elementAt(17)).doubleValue(); number_nodes++; leftnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(4), pos_left, neg_left, wpos_left_tempered, wneg_left_tempered, wpos_left_codensity, wneg_left_codensity); leftnn.compute_prediction(t_leaf); // System.out.println("left_leaf : " + t_leaf + ", wpos_left_codensity = " + // wpos_left_codensity + ", wneg_left_codensity = " + wneg_left_codensity); leftnn.continuous_features_indexes_for_split_copy_from(nn); leftnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.LEFT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, leftnn); number_nodes++; rightnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(5), pos_right, neg_right, wpos_right_tempered, wneg_right_tempered, wpos_right_codensity, wneg_right_codensity); rightnn.compute_prediction(t_leaf); // System.out.println("right_leaf : " + t_leaf + ", wpos_right_codensity = " + // wpos_right_codensity + ", wneg_right_codensity = " + wneg_right_codensity); rightnn.continuous_features_indexes_for_split_copy_from(nn); rightnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.RIGHT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, rightnn); if (nn.depth + 1 > depth) depth = nn.depth + 1; nn.left_child = leftnn; nn.right_child = rightnn; nsplits++; } if (number_nodes >= max_size) stop = true; } while (!stop); // updates leaves in tree leaves = new Vector(); for (j = 0; j < try_leaves.size(); j++) leaves.addElement(try_leaves.elementAt(j)); } public void init(double tt) { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); Vector indexes = new Vector(); Example e; int pos = 0, neg = 0; double wpos_tempered = 0.0, wneg_tempered = 0.0, wpos_codensity = 0.0, wneg_codensity = 0.0, alpha_leaf; for (i = 0; i < ne; i++) { indexes.addElement(new Integer(i)); e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.is_positive_noisy()) { pos++; wpos_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wpos_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } else { neg++; wneg_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wneg_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } } number_nodes = 1; root = new DecisionTreeNode( this, number_nodes, 0, split_CV, indexes, pos, neg, wpos_tempered, wneg_tempered, wpos_codensity, wneg_codensity); root.init_continuous_features_indexes_for_split(); depth = 0; // System.out.println("tt = " + tt + ", root_leaf : " + root + ", wpos_codensity = " + // wpos_codensity + ", wneg_codensity = " + wneg_codensity); root.compute_prediction(myBoost.tempered_t); leaves = new Vector(); leaves.addElement(root); } public DecisionTreeNode get_leaf(Example ee) { // returns the leaf reached by the example DecisionTreeNode nn = root; Feature f; while (!nn.is_leaf) { f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return nn; } public DecisionTreeNode get_leaf_MonotonicTreeGraph(Example ee) { // returns the monotonic node reached by the example // (builds a strictly monotonic path of nodes to a leaf, used the last one in the path; this is // a prediction node in the corresponding MonotonicTreeGraph) DecisionTreeNode nn = root; double best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); DecisionTreeNode ret = root; Feature f; while (!nn.is_leaf) { if (Math.abs(nn.node_prediction_from_boosting_weights) > best_prediction) { best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); ret = nn; } f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return ret; } public double leveraging_mu() { if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) return leveraging_mu_tempered_loss(); else if (myBoost.name.equals(Boost.KEY_NAME_LOG_LOSS)) return leveraging_mu_log_loss(); else Dataset.perror("DecisionTree.class :: no loss " + myBoost.name); return -1.0; } public double leveraging_mu_log_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); double rho_j = 0.0, max_absolute_pred = -1.0, output_e, tot_weight = 0.0, mu_j; Example e; for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); output_e = output_boosting(e); if ((i == 0) || (Math.abs(output_e) > max_absolute_pred)) max_absolute_pred = Math.abs(output_e); rho_j += (e.current_boosting_weight * output_e * e.noisy_normalized_class); tot_weight += e.current_boosting_weight; } rho_j /= (tot_weight * max_absolute_pred); tree_p_t = (1.0 + rho_j) / 2.0; tree_psi_t = Math.log((1.0 + rho_j) / (1.0 - rho_j)); tree_p_t_star = 1.0 / (1.0 + Math.exp(-max_absolute_pred)); if (tree_psi_t < 0.0) Dataset.perror("DecisionTree.class :: negative value tree_psi_t = " + tree_psi_t); // if ( (rho_j >= 1.0) || (rho_j <= -1.0) ) // Dataset.perror("DecisionTree.class :: impossible value rho_j = " + rho_j); REMOVE mu_j = (Math.log((1.0 + rho_j) / (1.0 - rho_j))) / max_absolute_pred; return mu_j; } public double leveraging_mu_tempered_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV), maxr, nbpos = 0, nbnull = 0; double r_j = 0.0, epsilon_j = 0.0, rho_j = 0.0, ww, mu_j, rat; Example e; // computes r_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight < 0.0) Dataset.perror("DecisionTree.class :: example has negative weight"); if (e.current_boosting_weight > 0.0) { if (myBoost.tempered_t != 1.0) rat = Math.abs(unweighted_edge_training(e)) / Math.pow(e.current_boosting_weight, 1.0 - myBoost.tempered_t); else rat = Math.abs(unweighted_edge_training(e)); if ((nbpos == 0) || (rat > r_j)) r_j = rat; nbpos++; } } if (r_j == 0.0) // h = 0 => mu = 0 return 0.0; // computes epsilon_j, see paper if (myBoost.tempered_t != 1.0) { for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight == 0.0) { rat = Math.abs(unweighted_edge_training(e)) / r_j; if ((nbnull == 0) || (rat > epsilon_j)) { epsilon_j = rat; } nbnull++; } } if (nbnull > 0) epsilon_j = Math.pow(epsilon_j, 1.0 / (1.0 - myBoost.tempered_t)); } // computes rho_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); ww = (e.current_boosting_weight > 0.0) ? e.current_boosting_weight : epsilon_j; rho_j += ww * unweighted_edge_training(e); } rho_j /= ((1.0 + (((double) nbnull) * Math.pow(epsilon_j, 2.0 - myBoost.tempered_t))) * r_j); if ((rho_j > 1.0) || (rho_j < -1.0)) Dataset.perror("DecisionTree.class :: rho_j = " + rho_j + " not in [-1,1]"); // System.out.println("BEFORE " + myBoost.tempered_t + ", rho = " + rho_j); mu_j = -Statistics.TEMPERED_LOG( (1.0 - rho_j) / Statistics.Q_MEAN(1.0 - rho_j, 1.0 + rho_j, 1.0 - myBoost.tempered_t), myBoost.tempered_t); // System.out.println("AFTER " + myBoost.tempered_t + ", mu = " + mu_j); if ((Double.isNaN(mu_j)) || (Double.isInfinite(mu_j))) { if (rho_j > 0.0) mu_j = Boost.MAX_PRED_VALUE; else if (rho_j < 0.0) mu_j = -Boost.MAX_PRED_VALUE; else Dataset.perror("DecisionTree.class :: inconsistency in the computation of rho_j"); TemperedBoostException.ADD(TemperedBoostException.NUMERICAL_ISSUES_INFINITE_MU); } mu_j /= r_j; return mu_j; } public double leveraging_alpha(double mu, Vector<Double> allzs) { if ((myBoost.tempered_t == 1.0) || (!myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))) return mu; double al = Math.pow( (double) myBoost.myDomain.myDS.train_size(split_CV), 1.0 - Statistics.STAR(myBoost.tempered_t)); int i; if (name > 0) { for (i = 0; i < name; i++) al *= Math.pow(allzs.elementAt(i).doubleValue(), 1.0 - myBoost.tempered_t); } al *= mu; return al; } public double output_boosting(Example ee) { DecisionTreeNode nn = get_leaf(ee); // if (ee.domain_id<SUF> // System.out.println("DT [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput(); return (nn.node_prediction_from_boosting_weights); } public double output_boosting_MonotonicTreeGraph(Example ee) { DecisionTreeNode nn = get_leaf_MonotonicTreeGraph(ee); // if (ee.domain_id == 1){ // System.out.println("MTG [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput_MonotonicTreeGraph(); return (nn.node_prediction_from_boosting_weights); } public double unweighted_edge_training(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting(ee)) * (ee.noisy_normalized_class)); } public double unweighted_edge_training_MonotonicTreeGraph(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting_MonotonicTreeGraph(ee)) * (ee.noisy_normalized_class)); } // safe checks methods public void check() { int i, j, ne = myBoost.myDomain.myDS.train_size(split_CV); DecisionTreeNode leaf1, leaf2; Example ee; for (i = 0; i < leaves.size(); i++) { leaf1 = (DecisionTreeNode) leaves.elementAt(i); for (j = 0; j < leaf1.train_fold_indexes_in_node.length; j++) { ee = myBoost.myDomain.myDS.train_example(split_CV, leaf1.train_fold_indexes_in_node[j]); leaf2 = get_leaf(ee); if (leaf1.name != leaf2.name) { Dataset.perror( "DecisionTree.class :: Example " + ee + " reaches leaf #" + leaf2 + " but is recorded for leaf #" + leaf1); } } } } }
1344_31
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class DecisionTree *****/ class DecisionTree implements Debuggable { public static boolean DISPLAY_INTERNAL_NODES_CLASSIFICATION = false; int name, depth; DecisionTreeNode root; // root of the tree Vector leaves; // list of leaves of the tree (potential growth here) Boost myBoost; int max_size; int split_CV; int number_nodes; // includes leaves double tree_p_t, tree_psi_t, tree_p_t_star; DecisionTree(int nn, Boost bb, int maxs, int split) { name = nn; root = null; myBoost = bb; max_size = maxs; split_CV = split; tree_p_t = tree_psi_t = tree_p_t_star = -1.0; } public String toString() { int i; String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n"; DecisionTreeNode dumn; v += root.display(new HashSet<Integer>()); v += "Leaves:"; Iterator it = leaves.iterator(); while (it.hasNext()) { v += " "; dumn = (DecisionTreeNode) it.next(); v += "#" + dumn.name + dumn.observations_string(); } v += ".\n"; return v; } public static void INSERT_WEIGHT_ORDER(Vector<DecisionTreeNode> all_nodes, DecisionTreeNode nn) { int k; if (all_nodes.size() == 0) all_nodes.addElement(nn); else { k = 0; while ((k < all_nodes.size()) && (nn.train_fold_indexes_in_node.length < all_nodes.elementAt(k).train_fold_indexes_in_node.length)) k++; all_nodes.insertElementAt(nn, k); } } public void grow_heavy_first() { // grows the heaviest grow-able leaf // heavy = wrt the total # examples reaching the node Vector vin, vvv; boolean stop = false; DecisionTreeNode nn, leftnn, rightnn; int i, j, k, l, ibest, pos_left, neg_left, pos_right, neg_right, nsplits = 0; double wpos_left_tempered, wneg_left_tempered, wpos_right_tempered, wneg_right_tempered, t_leaf = myBoost.tempered_t, w_leaf_codensity; double wpos_left_codensity, wneg_left_codensity, wpos_right_codensity, wneg_right_codensity; Vector<DecisionTreeNode> try_leaves = null; // leaves that will be tried to grow Vector candidate_split, dumv; try_leaves = new Vector<>(); for (j = 0; j < leaves.size(); j++) DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, (DecisionTreeNode) leaves.elementAt(j)); do { do { nn = ((DecisionTreeNode) try_leaves.elementAt(0)); candidate_split = nn.bestSplit(t_leaf); if (candidate_split == null) try_leaves.removeElementAt(0); } while ((try_leaves.size() > 0) && (candidate_split == null)); if (candidate_split == null) stop = true; else { vin = candidate_split; nn.is_leaf = false; try_leaves.removeElementAt(0); // nn.node_prediction_from_boosting_weights = nn.node_prediction_from_cardinals = 0.0; nn.feature_node_index = ((Integer) vin.elementAt(2)).intValue(); nn.feature_node_test_index = ((Integer) vin.elementAt(3)).intValue(); pos_left = ((Integer) vin.elementAt(6)).intValue(); neg_left = ((Integer) vin.elementAt(7)).intValue(); pos_right = ((Integer) vin.elementAt(8)).intValue(); neg_right = ((Integer) vin.elementAt(9)).intValue(); wpos_left_tempered = ((Double) vin.elementAt(10)).doubleValue(); wneg_left_tempered = ((Double) vin.elementAt(11)).doubleValue(); wpos_right_tempered = ((Double) vin.elementAt(12)).doubleValue(); wneg_right_tempered = ((Double) vin.elementAt(13)).doubleValue(); wpos_left_codensity = ((Double) vin.elementAt(14)).doubleValue(); wneg_left_codensity = ((Double) vin.elementAt(15)).doubleValue(); wpos_right_codensity = ((Double) vin.elementAt(16)).doubleValue(); wneg_right_codensity = ((Double) vin.elementAt(17)).doubleValue(); number_nodes++; leftnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(4), pos_left, neg_left, wpos_left_tempered, wneg_left_tempered, wpos_left_codensity, wneg_left_codensity); leftnn.compute_prediction(t_leaf); // System.out.println("left_leaf : " + t_leaf + ", wpos_left_codensity = " + // wpos_left_codensity + ", wneg_left_codensity = " + wneg_left_codensity); leftnn.continuous_features_indexes_for_split_copy_from(nn); leftnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.LEFT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, leftnn); number_nodes++; rightnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(5), pos_right, neg_right, wpos_right_tempered, wneg_right_tempered, wpos_right_codensity, wneg_right_codensity); rightnn.compute_prediction(t_leaf); // System.out.println("right_leaf : " + t_leaf + ", wpos_right_codensity = " + // wpos_right_codensity + ", wneg_right_codensity = " + wneg_right_codensity); rightnn.continuous_features_indexes_for_split_copy_from(nn); rightnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.RIGHT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, rightnn); if (nn.depth + 1 > depth) depth = nn.depth + 1; nn.left_child = leftnn; nn.right_child = rightnn; nsplits++; } if (number_nodes >= max_size) stop = true; } while (!stop); // updates leaves in tree leaves = new Vector(); for (j = 0; j < try_leaves.size(); j++) leaves.addElement(try_leaves.elementAt(j)); } public void init(double tt) { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); Vector indexes = new Vector(); Example e; int pos = 0, neg = 0; double wpos_tempered = 0.0, wneg_tempered = 0.0, wpos_codensity = 0.0, wneg_codensity = 0.0, alpha_leaf; for (i = 0; i < ne; i++) { indexes.addElement(new Integer(i)); e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.is_positive_noisy()) { pos++; wpos_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wpos_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } else { neg++; wneg_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wneg_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } } number_nodes = 1; root = new DecisionTreeNode( this, number_nodes, 0, split_CV, indexes, pos, neg, wpos_tempered, wneg_tempered, wpos_codensity, wneg_codensity); root.init_continuous_features_indexes_for_split(); depth = 0; // System.out.println("tt = " + tt + ", root_leaf : " + root + ", wpos_codensity = " + // wpos_codensity + ", wneg_codensity = " + wneg_codensity); root.compute_prediction(myBoost.tempered_t); leaves = new Vector(); leaves.addElement(root); } public DecisionTreeNode get_leaf(Example ee) { // returns the leaf reached by the example DecisionTreeNode nn = root; Feature f; while (!nn.is_leaf) { f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return nn; } public DecisionTreeNode get_leaf_MonotonicTreeGraph(Example ee) { // returns the monotonic node reached by the example // (builds a strictly monotonic path of nodes to a leaf, used the last one in the path; this is // a prediction node in the corresponding MonotonicTreeGraph) DecisionTreeNode nn = root; double best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); DecisionTreeNode ret = root; Feature f; while (!nn.is_leaf) { if (Math.abs(nn.node_prediction_from_boosting_weights) > best_prediction) { best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); ret = nn; } f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return ret; } public double leveraging_mu() { if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) return leveraging_mu_tempered_loss(); else if (myBoost.name.equals(Boost.KEY_NAME_LOG_LOSS)) return leveraging_mu_log_loss(); else Dataset.perror("DecisionTree.class :: no loss " + myBoost.name); return -1.0; } public double leveraging_mu_log_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); double rho_j = 0.0, max_absolute_pred = -1.0, output_e, tot_weight = 0.0, mu_j; Example e; for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); output_e = output_boosting(e); if ((i == 0) || (Math.abs(output_e) > max_absolute_pred)) max_absolute_pred = Math.abs(output_e); rho_j += (e.current_boosting_weight * output_e * e.noisy_normalized_class); tot_weight += e.current_boosting_weight; } rho_j /= (tot_weight * max_absolute_pred); tree_p_t = (1.0 + rho_j) / 2.0; tree_psi_t = Math.log((1.0 + rho_j) / (1.0 - rho_j)); tree_p_t_star = 1.0 / (1.0 + Math.exp(-max_absolute_pred)); if (tree_psi_t < 0.0) Dataset.perror("DecisionTree.class :: negative value tree_psi_t = " + tree_psi_t); // if ( (rho_j >= 1.0) || (rho_j <= -1.0) ) // Dataset.perror("DecisionTree.class :: impossible value rho_j = " + rho_j); REMOVE mu_j = (Math.log((1.0 + rho_j) / (1.0 - rho_j))) / max_absolute_pred; return mu_j; } public double leveraging_mu_tempered_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV), maxr, nbpos = 0, nbnull = 0; double r_j = 0.0, epsilon_j = 0.0, rho_j = 0.0, ww, mu_j, rat; Example e; // computes r_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight < 0.0) Dataset.perror("DecisionTree.class :: example has negative weight"); if (e.current_boosting_weight > 0.0) { if (myBoost.tempered_t != 1.0) rat = Math.abs(unweighted_edge_training(e)) / Math.pow(e.current_boosting_weight, 1.0 - myBoost.tempered_t); else rat = Math.abs(unweighted_edge_training(e)); if ((nbpos == 0) || (rat > r_j)) r_j = rat; nbpos++; } } if (r_j == 0.0) // h = 0 => mu = 0 return 0.0; // computes epsilon_j, see paper if (myBoost.tempered_t != 1.0) { for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight == 0.0) { rat = Math.abs(unweighted_edge_training(e)) / r_j; if ((nbnull == 0) || (rat > epsilon_j)) { epsilon_j = rat; } nbnull++; } } if (nbnull > 0) epsilon_j = Math.pow(epsilon_j, 1.0 / (1.0 - myBoost.tempered_t)); } // computes rho_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); ww = (e.current_boosting_weight > 0.0) ? e.current_boosting_weight : epsilon_j; rho_j += ww * unweighted_edge_training(e); } rho_j /= ((1.0 + (((double) nbnull) * Math.pow(epsilon_j, 2.0 - myBoost.tempered_t))) * r_j); if ((rho_j > 1.0) || (rho_j < -1.0)) Dataset.perror("DecisionTree.class :: rho_j = " + rho_j + " not in [-1,1]"); // System.out.println("BEFORE " + myBoost.tempered_t + ", rho = " + rho_j); mu_j = -Statistics.TEMPERED_LOG( (1.0 - rho_j) / Statistics.Q_MEAN(1.0 - rho_j, 1.0 + rho_j, 1.0 - myBoost.tempered_t), myBoost.tempered_t); // System.out.println("AFTER " + myBoost.tempered_t + ", mu = " + mu_j); if ((Double.isNaN(mu_j)) || (Double.isInfinite(mu_j))) { if (rho_j > 0.0) mu_j = Boost.MAX_PRED_VALUE; else if (rho_j < 0.0) mu_j = -Boost.MAX_PRED_VALUE; else Dataset.perror("DecisionTree.class :: inconsistency in the computation of rho_j"); TemperedBoostException.ADD(TemperedBoostException.NUMERICAL_ISSUES_INFINITE_MU); } mu_j /= r_j; return mu_j; } public double leveraging_alpha(double mu, Vector<Double> allzs) { if ((myBoost.tempered_t == 1.0) || (!myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))) return mu; double al = Math.pow( (double) myBoost.myDomain.myDS.train_size(split_CV), 1.0 - Statistics.STAR(myBoost.tempered_t)); int i; if (name > 0) { for (i = 0; i < name; i++) al *= Math.pow(allzs.elementAt(i).doubleValue(), 1.0 - myBoost.tempered_t); } al *= mu; return al; } public double output_boosting(Example ee) { DecisionTreeNode nn = get_leaf(ee); // if (ee.domain_id == 1){ // System.out.println("DT [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput(); return (nn.node_prediction_from_boosting_weights); } public double output_boosting_MonotonicTreeGraph(Example ee) { DecisionTreeNode nn = get_leaf_MonotonicTreeGraph(ee); // if (ee.domain_id == 1){ // System.out.println("MTG [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput_MonotonicTreeGraph(); return (nn.node_prediction_from_boosting_weights); } public double unweighted_edge_training(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting(ee)) * (ee.noisy_normalized_class)); } public double unweighted_edge_training_MonotonicTreeGraph(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting_MonotonicTreeGraph(ee)) * (ee.noisy_normalized_class)); } // safe checks methods public void check() { int i, j, ne = myBoost.myDomain.myDS.train_size(split_CV); DecisionTreeNode leaf1, leaf2; Example ee; for (i = 0; i < leaves.size(); i++) { leaf1 = (DecisionTreeNode) leaves.elementAt(i); for (j = 0; j < leaf1.train_fold_indexes_in_node.length; j++) { ee = myBoost.myDomain.myDS.train_example(split_CV, leaf1.train_fold_indexes_in_node[j]); leaf2 = get_leaf(ee); if (leaf1.name != leaf2.name) { Dataset.perror( "DecisionTree.class :: Example " + ee + " reaches leaf #" + leaf2 + " but is recorded for leaf #" + leaf1); } } } } }
google-research/google-research
tempered_boosting/DecisionTree.java
5,313
// if (ee.domain_id == 1){
line_comment
nl
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class DecisionTree *****/ class DecisionTree implements Debuggable { public static boolean DISPLAY_INTERNAL_NODES_CLASSIFICATION = false; int name, depth; DecisionTreeNode root; // root of the tree Vector leaves; // list of leaves of the tree (potential growth here) Boost myBoost; int max_size; int split_CV; int number_nodes; // includes leaves double tree_p_t, tree_psi_t, tree_p_t_star; DecisionTree(int nn, Boost bb, int maxs, int split) { name = nn; root = null; myBoost = bb; max_size = maxs; split_CV = split; tree_p_t = tree_psi_t = tree_p_t_star = -1.0; } public String toString() { int i; String v = "(name = #" + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n"; DecisionTreeNode dumn; v += root.display(new HashSet<Integer>()); v += "Leaves:"; Iterator it = leaves.iterator(); while (it.hasNext()) { v += " "; dumn = (DecisionTreeNode) it.next(); v += "#" + dumn.name + dumn.observations_string(); } v += ".\n"; return v; } public static void INSERT_WEIGHT_ORDER(Vector<DecisionTreeNode> all_nodes, DecisionTreeNode nn) { int k; if (all_nodes.size() == 0) all_nodes.addElement(nn); else { k = 0; while ((k < all_nodes.size()) && (nn.train_fold_indexes_in_node.length < all_nodes.elementAt(k).train_fold_indexes_in_node.length)) k++; all_nodes.insertElementAt(nn, k); } } public void grow_heavy_first() { // grows the heaviest grow-able leaf // heavy = wrt the total # examples reaching the node Vector vin, vvv; boolean stop = false; DecisionTreeNode nn, leftnn, rightnn; int i, j, k, l, ibest, pos_left, neg_left, pos_right, neg_right, nsplits = 0; double wpos_left_tempered, wneg_left_tempered, wpos_right_tempered, wneg_right_tempered, t_leaf = myBoost.tempered_t, w_leaf_codensity; double wpos_left_codensity, wneg_left_codensity, wpos_right_codensity, wneg_right_codensity; Vector<DecisionTreeNode> try_leaves = null; // leaves that will be tried to grow Vector candidate_split, dumv; try_leaves = new Vector<>(); for (j = 0; j < leaves.size(); j++) DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, (DecisionTreeNode) leaves.elementAt(j)); do { do { nn = ((DecisionTreeNode) try_leaves.elementAt(0)); candidate_split = nn.bestSplit(t_leaf); if (candidate_split == null) try_leaves.removeElementAt(0); } while ((try_leaves.size() > 0) && (candidate_split == null)); if (candidate_split == null) stop = true; else { vin = candidate_split; nn.is_leaf = false; try_leaves.removeElementAt(0); // nn.node_prediction_from_boosting_weights = nn.node_prediction_from_cardinals = 0.0; nn.feature_node_index = ((Integer) vin.elementAt(2)).intValue(); nn.feature_node_test_index = ((Integer) vin.elementAt(3)).intValue(); pos_left = ((Integer) vin.elementAt(6)).intValue(); neg_left = ((Integer) vin.elementAt(7)).intValue(); pos_right = ((Integer) vin.elementAt(8)).intValue(); neg_right = ((Integer) vin.elementAt(9)).intValue(); wpos_left_tempered = ((Double) vin.elementAt(10)).doubleValue(); wneg_left_tempered = ((Double) vin.elementAt(11)).doubleValue(); wpos_right_tempered = ((Double) vin.elementAt(12)).doubleValue(); wneg_right_tempered = ((Double) vin.elementAt(13)).doubleValue(); wpos_left_codensity = ((Double) vin.elementAt(14)).doubleValue(); wneg_left_codensity = ((Double) vin.elementAt(15)).doubleValue(); wpos_right_codensity = ((Double) vin.elementAt(16)).doubleValue(); wneg_right_codensity = ((Double) vin.elementAt(17)).doubleValue(); number_nodes++; leftnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(4), pos_left, neg_left, wpos_left_tempered, wneg_left_tempered, wpos_left_codensity, wneg_left_codensity); leftnn.compute_prediction(t_leaf); // System.out.println("left_leaf : " + t_leaf + ", wpos_left_codensity = " + // wpos_left_codensity + ", wneg_left_codensity = " + wneg_left_codensity); leftnn.continuous_features_indexes_for_split_copy_from(nn); leftnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.LEFT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, leftnn); number_nodes++; rightnn = new DecisionTreeNode( this, number_nodes, nn.depth + 1, split_CV, (Vector) vin.elementAt(5), pos_right, neg_right, wpos_right_tempered, wneg_right_tempered, wpos_right_codensity, wneg_right_codensity); rightnn.compute_prediction(t_leaf); // System.out.println("right_leaf : " + t_leaf + ", wpos_right_codensity = " + // wpos_right_codensity + ", wneg_right_codensity = " + wneg_right_codensity); rightnn.continuous_features_indexes_for_split_copy_from(nn); rightnn.continuous_features_indexes_for_split_update_child( nn.feature_node_index, nn.feature_node_test_index, DecisionTreeNode.RIGHT_CHILD); DecisionTree.INSERT_WEIGHT_ORDER(try_leaves, rightnn); if (nn.depth + 1 > depth) depth = nn.depth + 1; nn.left_child = leftnn; nn.right_child = rightnn; nsplits++; } if (number_nodes >= max_size) stop = true; } while (!stop); // updates leaves in tree leaves = new Vector(); for (j = 0; j < try_leaves.size(); j++) leaves.addElement(try_leaves.elementAt(j)); } public void init(double tt) { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); Vector indexes = new Vector(); Example e; int pos = 0, neg = 0; double wpos_tempered = 0.0, wneg_tempered = 0.0, wpos_codensity = 0.0, wneg_codensity = 0.0, alpha_leaf; for (i = 0; i < ne; i++) { indexes.addElement(new Integer(i)); e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.is_positive_noisy()) { pos++; wpos_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wpos_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } else { neg++; wneg_tempered += e.current_boosting_weight; if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) wneg_codensity += Math.pow(e.current_boosting_weight, 2.0 - tt); else wpos_codensity = -1.0; // enforces checkable errors } } number_nodes = 1; root = new DecisionTreeNode( this, number_nodes, 0, split_CV, indexes, pos, neg, wpos_tempered, wneg_tempered, wpos_codensity, wneg_codensity); root.init_continuous_features_indexes_for_split(); depth = 0; // System.out.println("tt = " + tt + ", root_leaf : " + root + ", wpos_codensity = " + // wpos_codensity + ", wneg_codensity = " + wneg_codensity); root.compute_prediction(myBoost.tempered_t); leaves = new Vector(); leaves.addElement(root); } public DecisionTreeNode get_leaf(Example ee) { // returns the leaf reached by the example DecisionTreeNode nn = root; Feature f; while (!nn.is_leaf) { f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return nn; } public DecisionTreeNode get_leaf_MonotonicTreeGraph(Example ee) { // returns the monotonic node reached by the example // (builds a strictly monotonic path of nodes to a leaf, used the last one in the path; this is // a prediction node in the corresponding MonotonicTreeGraph) DecisionTreeNode nn = root; double best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); DecisionTreeNode ret = root; Feature f; while (!nn.is_leaf) { if (Math.abs(nn.node_prediction_from_boosting_weights) > best_prediction) { best_prediction = Math.abs(nn.node_prediction_from_boosting_weights); ret = nn; } f = (Feature) myBoost.myDomain.myDS.features.elementAt( myBoost .myDomain .myDS .index_observation_features_to_index_features[nn.feature_node_index]); if (f.example_goes_left(ee, nn.feature_node_index, nn.feature_node_test_index)) nn = nn.left_child; else nn = nn.right_child; } return ret; } public double leveraging_mu() { if (myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) return leveraging_mu_tempered_loss(); else if (myBoost.name.equals(Boost.KEY_NAME_LOG_LOSS)) return leveraging_mu_log_loss(); else Dataset.perror("DecisionTree.class :: no loss " + myBoost.name); return -1.0; } public double leveraging_mu_log_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV); double rho_j = 0.0, max_absolute_pred = -1.0, output_e, tot_weight = 0.0, mu_j; Example e; for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); output_e = output_boosting(e); if ((i == 0) || (Math.abs(output_e) > max_absolute_pred)) max_absolute_pred = Math.abs(output_e); rho_j += (e.current_boosting_weight * output_e * e.noisy_normalized_class); tot_weight += e.current_boosting_weight; } rho_j /= (tot_weight * max_absolute_pred); tree_p_t = (1.0 + rho_j) / 2.0; tree_psi_t = Math.log((1.0 + rho_j) / (1.0 - rho_j)); tree_p_t_star = 1.0 / (1.0 + Math.exp(-max_absolute_pred)); if (tree_psi_t < 0.0) Dataset.perror("DecisionTree.class :: negative value tree_psi_t = " + tree_psi_t); // if ( (rho_j >= 1.0) || (rho_j <= -1.0) ) // Dataset.perror("DecisionTree.class :: impossible value rho_j = " + rho_j); REMOVE mu_j = (Math.log((1.0 + rho_j) / (1.0 - rho_j))) / max_absolute_pred; return mu_j; } public double leveraging_mu_tempered_loss() { int i, ne = myBoost.myDomain.myDS.train_size(split_CV), maxr, nbpos = 0, nbnull = 0; double r_j = 0.0, epsilon_j = 0.0, rho_j = 0.0, ww, mu_j, rat; Example e; // computes r_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight < 0.0) Dataset.perror("DecisionTree.class :: example has negative weight"); if (e.current_boosting_weight > 0.0) { if (myBoost.tempered_t != 1.0) rat = Math.abs(unweighted_edge_training(e)) / Math.pow(e.current_boosting_weight, 1.0 - myBoost.tempered_t); else rat = Math.abs(unweighted_edge_training(e)); if ((nbpos == 0) || (rat > r_j)) r_j = rat; nbpos++; } } if (r_j == 0.0) // h = 0 => mu = 0 return 0.0; // computes epsilon_j, see paper if (myBoost.tempered_t != 1.0) { for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); if (e.current_boosting_weight == 0.0) { rat = Math.abs(unweighted_edge_training(e)) / r_j; if ((nbnull == 0) || (rat > epsilon_j)) { epsilon_j = rat; } nbnull++; } } if (nbnull > 0) epsilon_j = Math.pow(epsilon_j, 1.0 / (1.0 - myBoost.tempered_t)); } // computes rho_j, see paper for (i = 0; i < ne; i++) { e = myBoost.myDomain.myDS.train_example(split_CV, i); ww = (e.current_boosting_weight > 0.0) ? e.current_boosting_weight : epsilon_j; rho_j += ww * unweighted_edge_training(e); } rho_j /= ((1.0 + (((double) nbnull) * Math.pow(epsilon_j, 2.0 - myBoost.tempered_t))) * r_j); if ((rho_j > 1.0) || (rho_j < -1.0)) Dataset.perror("DecisionTree.class :: rho_j = " + rho_j + " not in [-1,1]"); // System.out.println("BEFORE " + myBoost.tempered_t + ", rho = " + rho_j); mu_j = -Statistics.TEMPERED_LOG( (1.0 - rho_j) / Statistics.Q_MEAN(1.0 - rho_j, 1.0 + rho_j, 1.0 - myBoost.tempered_t), myBoost.tempered_t); // System.out.println("AFTER " + myBoost.tempered_t + ", mu = " + mu_j); if ((Double.isNaN(mu_j)) || (Double.isInfinite(mu_j))) { if (rho_j > 0.0) mu_j = Boost.MAX_PRED_VALUE; else if (rho_j < 0.0) mu_j = -Boost.MAX_PRED_VALUE; else Dataset.perror("DecisionTree.class :: inconsistency in the computation of rho_j"); TemperedBoostException.ADD(TemperedBoostException.NUMERICAL_ISSUES_INFINITE_MU); } mu_j /= r_j; return mu_j; } public double leveraging_alpha(double mu, Vector<Double> allzs) { if ((myBoost.tempered_t == 1.0) || (!myBoost.name.equals(Boost.KEY_NAME_TEMPERED_LOSS))) return mu; double al = Math.pow( (double) myBoost.myDomain.myDS.train_size(split_CV), 1.0 - Statistics.STAR(myBoost.tempered_t)); int i; if (name > 0) { for (i = 0; i < name; i++) al *= Math.pow(allzs.elementAt(i).doubleValue(), 1.0 - myBoost.tempered_t); } al *= mu; return al; } public double output_boosting(Example ee) { DecisionTreeNode nn = get_leaf(ee); // if (ee.domain_id == 1){ // System.out.println("DT [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput(); return (nn.node_prediction_from_boosting_weights); } public double output_boosting_MonotonicTreeGraph(Example ee) { DecisionTreeNode nn = get_leaf_MonotonicTreeGraph(ee); // if (ee.domain_id<SUF> // System.out.println("MTG [" + nn.name + "," + nn.depth + "," + // nn.node_prediction_from_boosting_weights + "]"); // REMOVE // } nn.checkForOutput_MonotonicTreeGraph(); return (nn.node_prediction_from_boosting_weights); } public double unweighted_edge_training(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting(ee)) * (ee.noisy_normalized_class)); } public double unweighted_edge_training_MonotonicTreeGraph(Example ee) { // return y * this(ee) ; USE NOISY CLASS (if no noise, just the regular class) return ((output_boosting_MonotonicTreeGraph(ee)) * (ee.noisy_normalized_class)); } // safe checks methods public void check() { int i, j, ne = myBoost.myDomain.myDS.train_size(split_CV); DecisionTreeNode leaf1, leaf2; Example ee; for (i = 0; i < leaves.size(); i++) { leaf1 = (DecisionTreeNode) leaves.elementAt(i); for (j = 0; j < leaf1.train_fold_indexes_in_node.length; j++) { ee = myBoost.myDomain.myDS.train_example(split_CV, leaf1.train_fold_indexes_in_node[j]); leaf2 = get_leaf(ee); if (leaf1.name != leaf2.name) { Dataset.perror( "DecisionTree.class :: Example " + ee + " reaches leaf #" + leaf2 + " but is recorded for leaf #" + leaf1); } } } } }
1366_6
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84) /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84) /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84) /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
6,464
// meters (WGS 84)
line_comment
nl
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS<SUF> /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84) /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84) /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
1366_8
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84) /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84) /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84) /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
6,464
// meters (WGS 84)
line_comment
nl
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84) /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS<SUF> /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84) /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
1366_10
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84) /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84) /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS 84) /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
6,464
// meters (WGS 84)
line_comment
nl
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.geo; import org.apache.lucene.geo.GeoEncodingUtils; import org.apache.lucene.util.SloppyMath; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.GeoPointValues; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.support.MapXContentParser; import java.io.IOException; import java.util.Collections; public class GeoUtils { /** Maximum valid latitude in degrees. */ public static final double MAX_LAT = 90.0; /** Minimum valid latitude in degrees. */ public static final double MIN_LAT = -90.0; /** Maximum valid longitude in degrees. */ public static final double MAX_LON = 180.0; /** Minimum valid longitude in degrees. */ public static final double MIN_LON = -180.0; /** Earth ellipsoid major axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MAJOR_AXIS = 6378137.0; // meters (WGS 84) /** Earth ellipsoid minor axis defined by WGS 84 in meters */ public static final double EARTH_SEMI_MINOR_AXIS = 6356752.314245; // meters (WGS 84) /** Earth mean radius defined by WGS 84 in meters */ public static final double EARTH_MEAN_RADIUS = 6371008.7714D; // meters (WGS<SUF> /** Earth ellipsoid equator length in meters */ public static final double EARTH_EQUATOR = 2 * Math.PI * EARTH_SEMI_MAJOR_AXIS; /** Earth ellipsoid polar distance in meters */ public static final double EARTH_POLAR_DISTANCE = Math.PI * EARTH_SEMI_MINOR_AXIS; /** rounding error for quantized latitude and longitude values */ public static final double TOLERANCE = 1E-6; private static final int QUAD_MAX_LEVELS_POSSIBLE = 50; private static final int GEOHASH_MAX_LEVELS_POSSIBLE = 24; /** Returns true if latitude is actually a valid latitude value.*/ public static boolean isValidLatitude(double latitude) { if (Double.isNaN(latitude) || Double.isInfinite(latitude) || latitude < GeoUtils.MIN_LAT || latitude > GeoUtils.MAX_LAT) { return false; } return true; } /** Returns true if longitude is actually a valid longitude value. */ public static boolean isValidLongitude(double longitude) { if (Double.isNaN(longitude) || Double.isInfinite(longitude) || longitude < GeoUtils.MIN_LON || longitude > GeoUtils.MAX_LON) { return false; } return true; } /** * Calculate the width (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the width of cells at level in meters */ public static double geoHashCellWidth(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_EQUATOR / (1L << ((((level + 1) / 2) * 3) + ((level / 2) * 2))); } /** * Calculate the width (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the width of cells at level in meters */ public static double quadTreeCellWidth(int level) { assert level >= 0; return EARTH_EQUATOR / (1L << level); } /** * Calculate the height (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the height of cells at level in meters */ public static double geoHashCellHeight(int level) { assert level >= 0; // Geohash cells are split into 32 cells at each level. the grid // alternates at each level between a 8x4 and a 4x8 grid return EARTH_POLAR_DISTANCE / (1L << ((((level + 1) / 2) * 2) + ((level / 2) * 3))); } /** * Calculate the height (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the height of cells at level in meters */ public static double quadTreeCellHeight(int level) { assert level >= 0; return EARTH_POLAR_DISTANCE / (1L << level); } /** * Calculate the size (in meters) of geohash cells at a specific level * @param level geohash level must be greater or equal to zero * @return the size of cells at level in meters */ public static double geoHashCellSize(int level) { assert level >= 0; final double w = geoHashCellWidth(level); final double h = geoHashCellHeight(level); return Math.sqrt(w * w + h * h); } /** * Calculate the size (in meters) of quadtree cells at a specific level * @param level quadtree level must be greater or equal to zero * @return the size of cells at level in meters */ public static double quadTreeCellSize(int level) { assert level >= 0; return Math.sqrt(EARTH_POLAR_DISTANCE * EARTH_POLAR_DISTANCE + EARTH_EQUATOR * EARTH_EQUATOR) / (1L << level); } /** * Calculate the number of levels needed for a specific precision. Quadtree * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater than zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return QUAD_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final long part = Math.round(Math.ceil(EARTH_EQUATOR / width)); final int level = Long.SIZE - Long.numberOfLeadingZeros(part) - 1; // (log_2) return (part <= (1L << level)) ? level : (level + 1); // adjust level } } /** * Calculate the number of levels needed for a specific precision. QuadTree * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int quadTreeLevelsForPrecision(String distance) { return quadTreeLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param meters Maximum size of cells in meters (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(double meters) { assert meters >= 0; if (meters == 0) { return GEOHASH_MAX_LEVELS_POSSIBLE; } else { final double ratio = 1 + (EARTH_POLAR_DISTANCE / EARTH_EQUATOR); // cell ratio final double width = Math.sqrt((meters * meters) / (ratio * ratio)); // convert to cell width final double part = Math.ceil(EARTH_EQUATOR / width); if (part == 1) return 1; final int bits = (int) Math.round(Math.ceil(Math.log(part) / Math.log(2))); final int full = bits / 5; // number of 5 bit subdivisions final int left = bits - full * 5; // bit representing the last level final int even = full + (left > 0 ? 1 : 0); // number of even levels final int odd = full + (left > 3 ? 1 : 0); // number of odd levels return even + odd; } } /** * Calculate the number of levels needed for a specific precision. GeoHash * cells will not exceed the specified size (diagonal) of the precision. * @param distance Maximum size of cells as unit string (must greater or equal to zero) * @return levels need to achieve precision */ public static int geoHashLevelsForPrecision(String distance) { return geoHashLevelsForPrecision(DistanceUnit.METERS.parse(distance, DistanceUnit.DEFAULT)); } /** * Normalize longitude to lie within the -180 (exclusive) to 180 (inclusive) range. * * @param lon Longitude to normalize * @return The normalized longitude. */ public static double normalizeLon(double lon) { if (lon > 180d || lon <= -180d) { lon = centeredModulus(lon, 360); } // avoid -0.0 return lon + 0d; } /** * Normalize latitude to lie within the -90 to 90 (both inclusive) range. * <p> * Note: You should not normalize longitude and latitude separately, * because when normalizing latitude it may be necessary to * add a shift of 180&deg; in the longitude. * For this purpose, you should call the * {@link #normalizePoint(GeoPoint)} function. * * @param lat Latitude to normalize * @return The normalized latitude. * @see #normalizePoint(GeoPoint) */ public static double normalizeLat(double lat) { if (lat > 90d || lat < -90d) { lat = centeredModulus(lat, 360); if (lat < -90) { lat = -180 - lat; } else if (lat > 90) { lat = 180 - lat; } } // avoid -0.0 return lat + 0d; } /** * Normalize the geo {@code Point} for its coordinates to lie within their * respective normalized ranges. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * * @param point The point to normalize in-place. */ public static void normalizePoint(GeoPoint point) { normalizePoint(point, true, true); } /** * Normalize the geo {@code Point} for the given coordinates to lie within * their respective normalized ranges. * <p> * You can control which coordinate gets normalized with the two flags. * <p> * Note: A shift of 180&deg; is applied in the longitude if necessary, * in order to normalize properly the latitude. * If normalizing latitude but not longitude, it is assumed that * the longitude is in the form x+k*360, with x in ]-180;180], * and k is meaningful to the application. * Therefore x will be adjusted while keeping k preserved. * * @param point The point to normalize in-place. * @param normLat Whether to normalize latitude or leave it as is. * @param normLon Whether to normalize longitude. */ public static void normalizePoint(GeoPoint point, boolean normLat, boolean normLon) { double[] pt = { point.lon(), point.lat() }; normalizePoint(pt, normLon, normLat); point.reset(pt[1], pt[0]); } public static void normalizePoint(double[] lonLat) { normalizePoint(lonLat, true, true); } public static boolean needsNormalizeLat(double lat) { return lat > 90 || lat < -90; } public static boolean needsNormalizeLon(double lon) { return lon > 180 || lon < -180; } public static void normalizePoint(double[] lonLat, boolean normLon, boolean normLat) { assert lonLat != null && lonLat.length == 2; normLat = normLat && needsNormalizeLat(lonLat[1]); normLon = normLon && (needsNormalizeLon(lonLat[0]) || normLat); if (normLat) { lonLat[1] = centeredModulus(lonLat[1], 360); boolean shift = true; if (lonLat[1] < -90) { lonLat[1] = -180 - lonLat[1]; } else if (lonLat[1] > 90) { lonLat[1] = 180 - lonLat[1]; } else { // No need to shift the longitude, and the latitude is normalized shift = false; } if (shift) { if (normLon) { lonLat[0] += 180; } else { // Longitude won't be normalized, // keep it in the form x+k*360 (with x in ]-180;180]) // by only changing x, assuming k is meaningful for the user application. lonLat[0] += normalizeLon(lonLat[0]) > 0 ? -180 : 180; } } } if (normLon) { lonLat[0] = centeredModulus(lonLat[0], 360); } } public static double centeredModulus(double dividend, double divisor) { double rtn = dividend % divisor; if (rtn <= 0) { rtn += divisor; } if (rtn > divisor / 2) { rtn -= divisor; } return rtn; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, false); } /** * Parses the value as a geopoint. The following types of values are supported: * <p> * Object: has to contain either lat and lon or geohash or type and coordinates fields * <p> * String: expected to be in "latitude, longitude" format or a geohash * <p> * Array: two or more elements, the first element is longitude, the second is latitude, the rest is ignored if ignoreZValue is true */ public static GeoPoint parseGeoPoint(Object value, final boolean ignoreZValue) throws ElasticsearchParseException { try ( XContentParser parser = new MapXContentParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("null_value", value), null ) ) { parser.nextToken(); // start object parser.nextToken(); // field name parser.nextToken(); // field value return parseGeoPoint(parser, ignoreZValue); } catch (IOException ex) { throw new ElasticsearchParseException("error parsing geopoint", ex); } } /** * Represents the point of the geohash cell that should be used as the value of geohash */ public enum EffectivePoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT } /** * Parse a geopoint represented as an object, string or an array. If the geopoint is represented as a geohash, * the left bottom corner of the geohash cell is used as the geopoint coordinates.GeoBoundingBoxQueryBuilder.java */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { return parseGeoPoint(parser, ignoreZValue, EffectivePoint.BOTTOM_LEFT); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geo_point has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>Object: <pre>{&quot;type&quot;: <i>Point</i>, &quot;coordinates&quot;: <i>&lt;array of doubles&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param ignoreZValue {@link XContentParser} to not throw an error if 3 dimensional data is provided * @return new {@link GeoPoint} parsed from the parse */ public static GeoPoint parseGeoPoint(XContentParser parser, final boolean ignoreZValue, final EffectivePoint effectivePoint) throws IOException, ElasticsearchParseException { return geoPointParser.parsePoint( parser, ignoreZValue, value -> new GeoPoint().resetFromString(value, ignoreZValue, effectivePoint) ); } private static final GenericPointParser<GeoPoint> geoPointParser = new GenericPointParser<>("geo_point", "lon", "lat") { @Override public void assertZValue(boolean ignoreZValue, double zValue) { GeoPoint.assertZValue(ignoreZValue, zValue); } @Override public GeoPoint createPoint(double x, double y) { // GeoPoint takes lat,lon which is the reverse order from CartesianPoint return new GeoPoint(y, x); } @Override public String fieldError() { return "field must be either lat/lon, geohash string or type/coordinates"; } }; /** * Parse a {@link GeoPoint} from a string. The string must have one of the following forms: * * <ul> * <li>Latitude, Longitude form: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash form:: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * </ul> * * @param val a String to parse the value from * @return new parsed {@link GeoPoint} */ public static GeoPoint parseFromString(String val) { GeoPoint point = new GeoPoint(); return point.resetFromString(val, false, EffectivePoint.BOTTOM_LEFT); } /** * Parse a precision that can be expressed as an integer or a distance measure like "1km", "10m". * * The precision is expressed as a number between 1 and 12 and indicates the length of geohash * used to represent geo points. * * @param parser {@link XContentParser} to parse the value from * @return int representing precision */ public static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException { XContentParser.Token token = parser.currentToken(); if (token.equals(XContentParser.Token.VALUE_NUMBER)) { return XContentMapValues.nodeIntegerValue(parser.intValue()); } else { String precision = parser.text(); try { // we want to treat simple integer strings as precision levels, not distances return XContentMapValues.nodeIntegerValue(precision); } catch (NumberFormatException e) { // try to parse as a distance value final int parsedPrecision = GeoUtils.geoHashLevelsForPrecision(precision); try { return checkPrecisionRange(parsedPrecision); } catch (IllegalArgumentException e2) { // this happens when distance too small, so precision > 12. We'd like to see the original string throw new IllegalArgumentException("precision too high [" + precision + "]", e2); } } } } /** * Checks that the precision is within range supported by elasticsearch - between 1 and 12 * * Returns the precision value if it is in the range and throws an IllegalArgumentException if it * is outside the range. */ public static int checkPrecisionRange(int precision) { if ((precision < 1) || (precision > 12)) { throw new IllegalArgumentException("Invalid geohash aggregation precision of " + precision + ". Must be between 1 and 12."); } return precision; } /** Return the distance (in meters) between 2 lat,lon geo points using the haversine method implemented by lucene */ public static double arcDistance(double lat1, double lon1, double lat2, double lon2) { return SloppyMath.haversinMeters(lat1, lon1, lat2, lon2); } /** * Return the distance (in meters) between 2 lat,lon geo points using a simple tangential plane * this provides a faster alternative to {@link GeoUtils#arcDistance} but is inaccurate for distances greater than * 4 decimal degrees */ public static double planeDistance(double lat1, double lon1, double lat2, double lon2) { double x = Math.toRadians(lon2 - lon1) * Math.cos(Math.toRadians((lat2 + lat1) / 2.0)); double y = Math.toRadians(lat2 - lat1); return Math.sqrt(x * x + y * y) * EARTH_MEAN_RADIUS; } /** * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points * for each document. */ public static SortedNumericDoubleValues distanceValues( final GeoDistance distance, final DistanceUnit unit, final MultiGeoPointValues geoPointValues, final GeoPoint... fromPoints ) { final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues); if (singleValues != null && fromPoints.length == 1) { return FieldData.singleton(new NumericDoubleValues() { @Override public boolean advanceExact(int doc) throws IOException { return singleValues.advanceExact(doc); } @Override public double doubleValue() throws IOException { final GeoPoint from = fromPoints[0]; final GeoPoint to = singleValues.pointValue(); return distance.calculate(from.lat(), from.lon(), to.lat(), to.lon(), unit); } }); } else { return new SortingNumericDoubleValues() { @Override public boolean advanceExact(int target) throws IOException { if (geoPointValues.advanceExact(target)) { resize(geoPointValues.docValueCount() * fromPoints.length); int v = 0; for (int i = 0; i < geoPointValues.docValueCount(); ++i) { final GeoPoint point = geoPointValues.nextValue(); for (GeoPoint from : fromPoints) { values[v] = distance.calculate(from.lat(), from.lon(), point.lat(), point.lon(), unit); v++; } } sort(); return true; } else { return false; } } }; } } /** * Transforms the provided longitude to the equivalent in lucene quantize space. */ public static double quantizeLon(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon)); } /** * Transforms the provided latitude to the equivalent in lucene quantize space. */ public static double quantizeLat(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat)); } /** * Transforms the provided longitude to the previous longitude in lucene quantize space. */ public static double quantizeLonDown(double lon) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(lon) - 1); } /** * Transforms the provided latitude to the next latitude in lucene quantize space. */ public static double quantizeLatUp(double lat) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(lat) + 1); } private GeoUtils() {} }
1410_8
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen */ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen */ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen */ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
alibaba/atlas
atlas-core/src/main/java/android/taobao/atlas/hack/Hack.java
5,594
/* Should never happen */
block_comment
nl
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen<SUF>*/ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen */ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen */ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
1410_10
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen */ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen */ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen */ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
alibaba/atlas
atlas-core/src/main/java/android/taobao/atlas/hack/Hack.java
5,594
/* Should never happen */
block_comment
nl
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen */ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen<SUF>*/ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen */ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
1410_13
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen */ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen */ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen */ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
alibaba/atlas
atlas-core/src/main/java/android/taobao/atlas/hack/Hack.java
5,594
/* Should never happen */
block_comment
nl
/* * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * 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 android.taobao.atlas.hack; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException; import android.taobao.atlas.hack.Interception.InterceptionHandler; import android.util.Log; /** @author Oasis */ public class Hack { /** All hacks should be declared in a centralized point extending this class, typically as static * method, and call it in your application initialization stage to verify all the hack * assertions by catching exception thrown: * <pre> * class MyHacks extends HackDeclaration { * * static HackedField<Object, PackageManager> ContextImpl_mPackageManager; * static HackedField<Object, Map<String, IBinder>> ServiceManager_sCache; * * static void defineAndVerify() { * try { * ContextImpl_mPackageManager = Hack.into("android.app.ContextImpl").field("mPackageManager").ofType(PackageManager.class); * ServiceManager_sCache = Hack.into("android.os.ServiceManager").staticField("sCache").ofGenericType(Map.class) * * ... * } catch (HackAssertionException e) { * // Report the failure and activate fall-back strategy. * ... * } * } * } * <pre> * Thus we can verify them all together in an early application initialization stage. If any assertion * failed, a fall-back strategy is suggested. */ public static abstract class HackDeclaration { /** This exception is purposely defined as "protected" and not extending Exception to avoid * developers unconsciously catch it outside the centralized hacks declaration, which results * in potentially pre-checked usage of hacks. */ public static class HackAssertionException extends Throwable { private Class<?> mHackedClass; private String mHackedFieldName; private String mHackedMethodName; public HackAssertionException(final String e) { super(e); } public HackAssertionException(final Exception e) { super(e); } @Override public String toString() { return getCause() != null ? getClass().getName() + ": " + getCause() : super.toString(); } public Class<?> getHackedClass() { return mHackedClass; } public void setHackedClass(Class<?> mHackedClass) { this.mHackedClass = mHackedClass; } public String getHackedMethodName() { return mHackedMethodName; } public void setHackedMethodName(String methodName) { this.mHackedMethodName = methodName; } public String getHackedFieldName() { return mHackedFieldName; } public void setHackedFieldName(String fieldName) { this.mHackedFieldName = fieldName; } private static final long serialVersionUID = 1L; } } /** Use {@link Hack#setAssertionFailureHandler(AssertionFailureHandler) } to set the global handler */ public interface AssertionFailureHandler { /** @return whether the failure is handled and no need to throw out, return false to let it thrown */ boolean onAssertionFailure(HackAssertionException failure); } /** @beta */ public static class HackedField<C, T> { @SuppressWarnings("unchecked") // TODO: Add more check public <T2> HackedField<C, T2> ofGenericType(final Class<?> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public <T2> HackedField<C, T2> ofType(final Class<T2> type) throws HackAssertionException { if (mField != null && !type.isAssignableFrom(mField.getType())) fail(new HackAssertionException(new ClassCastException(mField + " is not of type " + type))); return (HackedField<C, T2>) this; } @SuppressWarnings("unchecked") public HackedField<C, T> ofType(final String type_name) throws HackAssertionException { try { return (HackedField<C, T>) ofType(Class.forName(type_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return this; } } /** Get current value of this field */ public T get(final C instance) { try { @SuppressWarnings("unchecked") final T value = (T) mField.get(instance); return value; } catch (final IllegalAccessException e) { e.printStackTrace(); //TBS.Ext.commitEvent("AtlasRuntimeException", AtlasConstant.ATLAS_RUNTIME_EXCEPTION, e.toString()); return null; /* Should never happen */ } } /** * Set value of this field * * <p>No type enforced here since most type mismatch can be easily tested and exposed early.</p> */ public void set(final C instance,final Object value) { try { mField.set(instance, value); } catch (final IllegalAccessException e) { e.printStackTrace(); /* Should never happen */ } } /** * Hijack the current instance of this field. * * <p><b>The instance must not be null at the time of hijacking</b>, or an IllegalStateException will be thrown. * * @param handler a invocation handler to implement the hijack logic. */ public void hijack(final C instance,final InterceptionHandler<?> handler) { final Object delegatee = get(instance); if (delegatee == null) throw new IllegalStateException("Cannot hijack null"); final Class<?>[] interfaces = delegatee.getClass().getInterfaces(); set(instance,Interception.proxy(delegatee, handler, interfaces)); } /** @param modifiers the modifiers this field must have */ HackedField(final Class<C> clazz, final String name, int modifiers) throws HackAssertionException { Field field = null; try { if (clazz == null) return; field = clazz.getDeclaredField(name); if (modifiers > 0 && (field.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(field + " does not match modifiers: " + modifiers)); field.setAccessible(true); } catch (final NoSuchFieldException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedFieldName(name); fail(hae); } finally { mField = field; } } private final Field mField; public Field getField() { return mField; } } public static class HackedMethod { private static final String TAG = "HackedMethod"; public Object invoke(final Object receiver, final Object... args) throws IllegalArgumentException, InvocationTargetException { Object obj = null; try { obj = mMethod.invoke(receiver, args); return obj; } catch (final IllegalAccessException e) { /* Should never happen<SUF>*/ e.printStackTrace(); } return obj; } HackedMethod(final Class<?> clazz, final String name, final Class<?>[] arg_types, int modifiers) throws HackAssertionException { Method method = null; try { if (clazz == null) return; method = clazz.getDeclaredMethod(name, arg_types); if (modifiers > 0 && (method.getModifiers() & modifiers) != modifiers) fail(new HackAssertionException(method + " does not match modifiers: " + modifiers)); method.setAccessible(true); } catch (final NoSuchMethodException e) { Log.e(TAG, "No such method: " + e.getMessage()); HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); hae.setHackedMethodName(name); fail(hae); } finally { mMethod = method; } } protected final Method mMethod; public Method getMethod() { return mMethod; } } public static class HackedConstructor { protected Constructor<?> mConstructor; HackedConstructor(final Class<?> clazz, final Class<?>[] arg_types) throws HackAssertionException { try { if (clazz == null) return; mConstructor = clazz.getDeclaredConstructor(arg_types); } catch (NoSuchMethodException e) { HackAssertionException hae = new HackAssertionException(e); hae.setHackedClass(clazz); fail(hae); } } public Object getInstance(final Object... arg_types) throws IllegalArgumentException { Object obj = null; mConstructor.setAccessible(true); try { obj = mConstructor.newInstance(arg_types); } catch (Exception e) { e.printStackTrace(); } return obj; } } public static class HackedClass<C> { public HackedField<C, Object> staticField(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, Modifier.STATIC); } public HackedField<C, Object> field(final String name) throws HackAssertionException { return new HackedField<C, Object>(mClass, name, 0); } public HackedMethod staticMethod(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, Modifier.STATIC); } public HackedMethod method(final String name, final Class<?>... arg_types) throws HackAssertionException { return new HackedMethod(mClass, name, arg_types, 0); } public HackedConstructor constructor(final Class<?>... arg_types) throws HackAssertionException { return new HackedConstructor(mClass, arg_types); } public HackedClass(final Class<C> clazz) { mClass = clazz; } protected Class<C> mClass; public Class<C> getmClass() { return mClass; } } public static <T> HackedClass<T> into(final Class<T> clazz) { return new HackedClass<T>(clazz); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> HackedClass<T> into(final String class_name) throws HackAssertionException { try { return new HackedClass(Class.forName(class_name)); } catch (final ClassNotFoundException e) { fail(new HackAssertionException(e)); return new HackedClass(null); // TODO: Better solution to avoid null? } } private static void fail(HackAssertionException e) throws HackAssertionException { if (sFailureHandler == null || ! sFailureHandler.onAssertionFailure(e)) throw e; } /** Specify a handler to deal with assertion failure, and decide whether the failure should be thrown. */ public static void setAssertionFailureHandler(AssertionFailureHandler handler) { sFailureHandler = handler; } private Hack() {} private static AssertionFailureHandler sFailureHandler; }
1413_30
/* * 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.jasper.compiler; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.el.ExpressionFactory; import jakarta.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; /** * A repository for various info about the translation unit under compilation. * * @author Kin-man Chung */ class PageInfo { private final List<String> imports; private final Map<String,Long> dependants; private final BeanRepository beanRepository; private final Set<String> varInfoNames; private final HashMap<String,TagLibraryInfo> taglibsMap; private final HashMap<String, String> jspPrefixMapper; private final HashMap<String, Deque<String>> xmlPrefixMapper; private final HashMap<String, Mark> nonCustomTagPrefixMap; private final String jspFile; private static final String defaultLanguage = "java"; private String language; private final String defaultExtends; private String xtends; private String contentType = null; private String session; private boolean isSession = true; private String bufferValue; private int buffer = 8*1024; private String autoFlush; private boolean isAutoFlush = true; private String isErrorPageValue; private boolean isErrorPage = false; private String errorPage = null; private String info; private boolean scriptless = false; private boolean scriptingInvalid = false; private String isELIgnoredValue; private boolean isELIgnored = false; // JSP 2.1 private String deferredSyntaxAllowedAsLiteralValue; private boolean deferredSyntaxAllowedAsLiteral = false; private final ExpressionFactory expressionFactory = ExpressionFactory.newInstance(); private String trimDirectiveWhitespacesValue; private boolean trimDirectiveWhitespaces = false; private String omitXmlDecl = null; private String doctypeName = null; private String doctypePublic = null; private String doctypeSystem = null; private boolean isJspPrefixHijacked; // Set of all element and attribute prefixes used in this translation unit private final HashSet<String> prefixes; private boolean hasJspRoot = false; private Collection<String> includePrelude; private Collection<String> includeCoda; private final List<String> pluginDcls; // Id's for tagplugin declarations // JSP 2.2 private boolean errorOnUndeclaredNamespace = false; // JSP 3.1 private String errorOnELNotFoundValue; private boolean errorOnELNotFound = false; private final boolean isTagFile; PageInfo(BeanRepository beanRepository, JspCompilationContext ctxt) { isTagFile = ctxt.isTagFile(); jspFile = ctxt.getJspFile(); defaultExtends = ctxt.getOptions().getJspServletBase(); this.beanRepository = beanRepository; this.varInfoNames = new HashSet<>(); this.taglibsMap = new HashMap<>(); this.jspPrefixMapper = new HashMap<>(); this.xmlPrefixMapper = new HashMap<>(); this.nonCustomTagPrefixMap = new HashMap<>(); this.dependants = new HashMap<>(); this.includePrelude = new ArrayList<>(); this.includeCoda = new ArrayList<>(); this.pluginDcls = new ArrayList<>(); this.prefixes = new HashSet<>(); // Enter standard imports this.imports = new ArrayList<>(Constants.STANDARD_IMPORTS); } public boolean isTagFile() { return isTagFile; } /** * Check if the plugin ID has been previously declared. Make a note * that this Id is now declared. * * @param id The plugin ID to check * * @return true if Id has been declared. */ public boolean isPluginDeclared(String id) { if (pluginDcls.contains(id)) { return true; } pluginDcls.add(id); return false; } public void addImports(List<String> imports) { this.imports.addAll(imports); } public void addImport(String imp) { this.imports.add(imp); } public List<String> getImports() { return imports; } public String getJspFile() { return jspFile; } public void addDependant(String d, Long lastModified) { if (!dependants.containsKey(d) && !jspFile.equals(d)) { dependants.put(d, lastModified); } } public Map<String,Long> getDependants() { return dependants; } public BeanRepository getBeanRepository() { return beanRepository; } public void setScriptless(boolean s) { scriptless = s; } public boolean isScriptless() { return scriptless; } public void setScriptingInvalid(boolean s) { scriptingInvalid = s; } public boolean isScriptingInvalid() { return scriptingInvalid; } public Collection<String> getIncludePrelude() { return includePrelude; } public void setIncludePrelude(Collection<String> prelude) { includePrelude = prelude; } public Collection<String> getIncludeCoda() { return includeCoda; } public void setIncludeCoda(Collection<String> coda) { includeCoda = coda; } public void setHasJspRoot(boolean s) { hasJspRoot = s; } public boolean hasJspRoot() { return hasJspRoot; } public String getOmitXmlDecl() { return omitXmlDecl; } public void setOmitXmlDecl(String omit) { omitXmlDecl = omit; } public String getDoctypeName() { return doctypeName; } public void setDoctypeName(String doctypeName) { this.doctypeName = doctypeName; } public String getDoctypeSystem() { return doctypeSystem; } public void setDoctypeSystem(String doctypeSystem) { this.doctypeSystem = doctypeSystem; } public String getDoctypePublic() { return doctypePublic; } public void setDoctypePublic(String doctypePublic) { this.doctypePublic = doctypePublic; } /* Tag library and XML namespace management methods */ public void setIsJspPrefixHijacked(boolean isHijacked) { isJspPrefixHijacked = isHijacked; } public boolean isJspPrefixHijacked() { return isJspPrefixHijacked; } /* * Adds the given prefix to the set of prefixes of this translation unit. * * @param prefix The prefix to add */ public void addPrefix(String prefix) { prefixes.add(prefix); } /* * Checks to see if this translation unit contains the given prefix. * * @param prefix The prefix to check * * @return true if this translation unit contains the given prefix, false * otherwise */ public boolean containsPrefix(String prefix) { return prefixes.contains(prefix); } /* * Maps the given URI to the given tag library. * * @param uri The URI to map * @param info The tag library to be associated with the given URI */ public void addTaglib(String uri, TagLibraryInfo info) { taglibsMap.put(uri, info); } /* * Gets the tag library corresponding to the given URI. * * @return Tag library corresponding to the given URI */ public TagLibraryInfo getTaglib(String uri) { return taglibsMap.get(uri); } /* * Gets the collection of tag libraries that are associated with a URI * * @return Collection of tag libraries that are associated with a URI */ public Collection<TagLibraryInfo> getTaglibs() { return taglibsMap.values(); } /* * Checks to see if the given URI is mapped to a tag library. * * @param uri The URI to map * * @return true if the given URI is mapped to a tag library, false * otherwise */ public boolean hasTaglib(String uri) { return taglibsMap.containsKey(uri); } /* * Maps the given prefix to the given URI. * * @param prefix The prefix to map * @param uri The URI to be associated with the given prefix */ public void addPrefixMapping(String prefix, String uri) { jspPrefixMapper.put(prefix, uri); } /* * Pushes the given URI onto the stack of URIs to which the given prefix * is mapped. * * @param prefix The prefix whose stack of URIs is to be pushed * @param uri The URI to be pushed onto the stack */ public void pushPrefixMapping(String prefix, String uri) { // Must be LinkedList as it needs to accept nulls xmlPrefixMapper.computeIfAbsent(prefix, k -> new LinkedList<>()).addFirst(uri); } /* * Removes the URI at the top of the stack of URIs to which the given * prefix is mapped. * * @param prefix The prefix whose stack of URIs is to be popped */ public void popPrefixMapping(String prefix) { Deque<String> stack = xmlPrefixMapper.get(prefix); stack.removeFirst(); } /* * Returns the URI to which the given prefix maps. * * @param prefix The prefix whose URI is sought * * @return The URI to which the given prefix maps */ public String getURI(String prefix) { String uri = null; Deque<String> stack = xmlPrefixMapper.get(prefix); if (stack == null || stack.size() == 0) { uri = jspPrefixMapper.get(prefix); } else { uri = stack.getFirst(); } return uri; } /* Page/Tag directive attributes */ /* * language */ public void setLanguage(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if (!"java".equalsIgnoreCase(value)) { if (pagedir) { err.jspError(n, "jsp.error.page.language.nonjava"); } else { err.jspError(n, "jsp.error.tag.language.nonjava"); } } language = value; } public String getLanguage(boolean useDefault) { return (language == null && useDefault ? defaultLanguage : language); } /* * extends */ public void setExtends(String value) { xtends = value; } /** * Gets the value of the 'extends' page directive attribute. * * @param useDefault TRUE if the default * (org.apache.jasper.runtime.HttpJspBase) should be returned if this * attribute has not been set, FALSE otherwise * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set and useDefault is TRUE */ public String getExtends(boolean useDefault) { return (xtends == null && useDefault ? defaultExtends : xtends); } /** * Gets the value of the 'extends' page directive attribute. * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set */ public String getExtends() { return getExtends(true); } /* * contentType */ public void setContentType(String value) { contentType = value; } public String getContentType() { return contentType; } /* * buffer */ public void setBufferValue(String value, Node n, ErrorDispatcher err) throws JasperException { if ("none".equalsIgnoreCase(value)) { buffer = 0; } else { if (value == null || !value.endsWith("kb")) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } try { @SuppressWarnings("null") // value can't be null here int k = Integer.parseInt(value.substring(0, value.length()-2)); buffer = k * 1024; } catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } } bufferValue = value; } public String getBufferValue() { return bufferValue; } public int getBuffer() { return buffer; } /* * session */ public void setSession(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isSession = true; } else if ("false".equalsIgnoreCase(value)) { isSession = false; } else { err.jspError(n, "jsp.error.page.invalid.session"); } session = value; } public String getSession() { return session; } public boolean isSession() { return isSession; } /* * autoFlush */ public void setAutoFlush(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isAutoFlush = true; } else if ("false".equalsIgnoreCase(value)) { isAutoFlush = false; } else { err.jspError(n, "jsp.error.autoFlush.invalid"); } autoFlush = value; } public String getAutoFlush() { return autoFlush; } public boolean isAutoFlush() { return isAutoFlush; } /* * info */ public void setInfo(String value) { info = value; } public String getInfo() { return info; } /* * errorPage */ public void setErrorPage(String value) { errorPage = value; } public String getErrorPage() { return errorPage; } /* * isErrorPage */ public void setIsErrorPage(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isErrorPage = true; } else if ("false".equalsIgnoreCase(value)) { isErrorPage = false; } else { err.jspError(n, "jsp.error.page.invalid.iserrorpage"); } isErrorPageValue = value; } public String getIsErrorPage() { return isErrorPageValue; } public boolean isErrorPage() { return isErrorPage; } /* * isELIgnored */ public void setIsELIgnored(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { isELIgnored = true; } else if ("false".equalsIgnoreCase(value)) { isELIgnored = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.iselignored"); } else { err.jspError(n, "jsp.error.tag.invalid.iselignored"); } } isELIgnoredValue = value; } /* * errorOnELNotFound */ public void setErrorOnELNotFound(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { errorOnELNotFound = true; } else if ("false".equalsIgnoreCase(value)) { errorOnELNotFound = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.errorOnELNotFound"); } else { err.jspError(n, "jsp.error.tag.invalid.errorOnELNotFound"); } } errorOnELNotFoundValue = value; } /* * deferredSyntaxAllowedAsLiteral */ public void setDeferredSyntaxAllowedAsLiteral(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { deferredSyntaxAllowedAsLiteral = true; } else if ("false".equalsIgnoreCase(value)) { deferredSyntaxAllowedAsLiteral = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.deferredsyntaxallowedasliteral"); } else { err.jspError(n, "jsp.error.tag.invalid.deferredsyntaxallowedasliteral"); } } deferredSyntaxAllowedAsLiteralValue = value; } /* * trimDirectiveWhitespaces */ public void setTrimDirectiveWhitespaces(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { trimDirectiveWhitespaces = true; } else if ("false".equalsIgnoreCase(value)) { trimDirectiveWhitespaces = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.trimdirectivewhitespaces"); } else { err.jspError(n, "jsp.error.tag.invalid.trimdirectivewhitespaces"); } } trimDirectiveWhitespacesValue = value; } public void setELIgnored(boolean s) { isELIgnored = s; } public String getIsELIgnored() { return isELIgnoredValue; } public boolean isELIgnored() { return isELIgnored; } public void setErrorOnELNotFound(boolean s) { errorOnELNotFound = s; } public String getErrorOnELNotFound() { return errorOnELNotFoundValue; } public boolean isErrorOnELNotFound() { return errorOnELNotFound; } public void putNonCustomTagPrefix(String prefix, Mark where) { nonCustomTagPrefixMap.put(prefix, where); } public Mark getNonCustomTagPrefix(String prefix) { return nonCustomTagPrefixMap.get(prefix); } public String getDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteralValue; } public boolean isDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteral; } public void setDeferredSyntaxAllowedAsLiteral(boolean isELDeferred) { this.deferredSyntaxAllowedAsLiteral = isELDeferred; } public ExpressionFactory getExpressionFactory() { return expressionFactory; } public String getTrimDirectiveWhitespaces() { return trimDirectiveWhitespacesValue; } public boolean isTrimDirectiveWhitespaces() { return trimDirectiveWhitespaces; } public void setTrimDirectiveWhitespaces(boolean trimDirectiveWhitespaces) { this.trimDirectiveWhitespaces = trimDirectiveWhitespaces; } public Set<String> getVarInfoNames() { return varInfoNames; } public boolean isErrorOnUndeclaredNamespace() { return errorOnUndeclaredNamespace; } public void setErrorOnUndeclaredNamespace( boolean errorOnUndeclaredNamespace) { this.errorOnUndeclaredNamespace = errorOnUndeclaredNamespace; } }
apache/tomcat
java/org/apache/jasper/compiler/PageInfo.java
5,206
/* * isErrorPage */
block_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.jasper.compiler; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.el.ExpressionFactory; import jakarta.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; /** * A repository for various info about the translation unit under compilation. * * @author Kin-man Chung */ class PageInfo { private final List<String> imports; private final Map<String,Long> dependants; private final BeanRepository beanRepository; private final Set<String> varInfoNames; private final HashMap<String,TagLibraryInfo> taglibsMap; private final HashMap<String, String> jspPrefixMapper; private final HashMap<String, Deque<String>> xmlPrefixMapper; private final HashMap<String, Mark> nonCustomTagPrefixMap; private final String jspFile; private static final String defaultLanguage = "java"; private String language; private final String defaultExtends; private String xtends; private String contentType = null; private String session; private boolean isSession = true; private String bufferValue; private int buffer = 8*1024; private String autoFlush; private boolean isAutoFlush = true; private String isErrorPageValue; private boolean isErrorPage = false; private String errorPage = null; private String info; private boolean scriptless = false; private boolean scriptingInvalid = false; private String isELIgnoredValue; private boolean isELIgnored = false; // JSP 2.1 private String deferredSyntaxAllowedAsLiteralValue; private boolean deferredSyntaxAllowedAsLiteral = false; private final ExpressionFactory expressionFactory = ExpressionFactory.newInstance(); private String trimDirectiveWhitespacesValue; private boolean trimDirectiveWhitespaces = false; private String omitXmlDecl = null; private String doctypeName = null; private String doctypePublic = null; private String doctypeSystem = null; private boolean isJspPrefixHijacked; // Set of all element and attribute prefixes used in this translation unit private final HashSet<String> prefixes; private boolean hasJspRoot = false; private Collection<String> includePrelude; private Collection<String> includeCoda; private final List<String> pluginDcls; // Id's for tagplugin declarations // JSP 2.2 private boolean errorOnUndeclaredNamespace = false; // JSP 3.1 private String errorOnELNotFoundValue; private boolean errorOnELNotFound = false; private final boolean isTagFile; PageInfo(BeanRepository beanRepository, JspCompilationContext ctxt) { isTagFile = ctxt.isTagFile(); jspFile = ctxt.getJspFile(); defaultExtends = ctxt.getOptions().getJspServletBase(); this.beanRepository = beanRepository; this.varInfoNames = new HashSet<>(); this.taglibsMap = new HashMap<>(); this.jspPrefixMapper = new HashMap<>(); this.xmlPrefixMapper = new HashMap<>(); this.nonCustomTagPrefixMap = new HashMap<>(); this.dependants = new HashMap<>(); this.includePrelude = new ArrayList<>(); this.includeCoda = new ArrayList<>(); this.pluginDcls = new ArrayList<>(); this.prefixes = new HashSet<>(); // Enter standard imports this.imports = new ArrayList<>(Constants.STANDARD_IMPORTS); } public boolean isTagFile() { return isTagFile; } /** * Check if the plugin ID has been previously declared. Make a note * that this Id is now declared. * * @param id The plugin ID to check * * @return true if Id has been declared. */ public boolean isPluginDeclared(String id) { if (pluginDcls.contains(id)) { return true; } pluginDcls.add(id); return false; } public void addImports(List<String> imports) { this.imports.addAll(imports); } public void addImport(String imp) { this.imports.add(imp); } public List<String> getImports() { return imports; } public String getJspFile() { return jspFile; } public void addDependant(String d, Long lastModified) { if (!dependants.containsKey(d) && !jspFile.equals(d)) { dependants.put(d, lastModified); } } public Map<String,Long> getDependants() { return dependants; } public BeanRepository getBeanRepository() { return beanRepository; } public void setScriptless(boolean s) { scriptless = s; } public boolean isScriptless() { return scriptless; } public void setScriptingInvalid(boolean s) { scriptingInvalid = s; } public boolean isScriptingInvalid() { return scriptingInvalid; } public Collection<String> getIncludePrelude() { return includePrelude; } public void setIncludePrelude(Collection<String> prelude) { includePrelude = prelude; } public Collection<String> getIncludeCoda() { return includeCoda; } public void setIncludeCoda(Collection<String> coda) { includeCoda = coda; } public void setHasJspRoot(boolean s) { hasJspRoot = s; } public boolean hasJspRoot() { return hasJspRoot; } public String getOmitXmlDecl() { return omitXmlDecl; } public void setOmitXmlDecl(String omit) { omitXmlDecl = omit; } public String getDoctypeName() { return doctypeName; } public void setDoctypeName(String doctypeName) { this.doctypeName = doctypeName; } public String getDoctypeSystem() { return doctypeSystem; } public void setDoctypeSystem(String doctypeSystem) { this.doctypeSystem = doctypeSystem; } public String getDoctypePublic() { return doctypePublic; } public void setDoctypePublic(String doctypePublic) { this.doctypePublic = doctypePublic; } /* Tag library and XML namespace management methods */ public void setIsJspPrefixHijacked(boolean isHijacked) { isJspPrefixHijacked = isHijacked; } public boolean isJspPrefixHijacked() { return isJspPrefixHijacked; } /* * Adds the given prefix to the set of prefixes of this translation unit. * * @param prefix The prefix to add */ public void addPrefix(String prefix) { prefixes.add(prefix); } /* * Checks to see if this translation unit contains the given prefix. * * @param prefix The prefix to check * * @return true if this translation unit contains the given prefix, false * otherwise */ public boolean containsPrefix(String prefix) { return prefixes.contains(prefix); } /* * Maps the given URI to the given tag library. * * @param uri The URI to map * @param info The tag library to be associated with the given URI */ public void addTaglib(String uri, TagLibraryInfo info) { taglibsMap.put(uri, info); } /* * Gets the tag library corresponding to the given URI. * * @return Tag library corresponding to the given URI */ public TagLibraryInfo getTaglib(String uri) { return taglibsMap.get(uri); } /* * Gets the collection of tag libraries that are associated with a URI * * @return Collection of tag libraries that are associated with a URI */ public Collection<TagLibraryInfo> getTaglibs() { return taglibsMap.values(); } /* * Checks to see if the given URI is mapped to a tag library. * * @param uri The URI to map * * @return true if the given URI is mapped to a tag library, false * otherwise */ public boolean hasTaglib(String uri) { return taglibsMap.containsKey(uri); } /* * Maps the given prefix to the given URI. * * @param prefix The prefix to map * @param uri The URI to be associated with the given prefix */ public void addPrefixMapping(String prefix, String uri) { jspPrefixMapper.put(prefix, uri); } /* * Pushes the given URI onto the stack of URIs to which the given prefix * is mapped. * * @param prefix The prefix whose stack of URIs is to be pushed * @param uri The URI to be pushed onto the stack */ public void pushPrefixMapping(String prefix, String uri) { // Must be LinkedList as it needs to accept nulls xmlPrefixMapper.computeIfAbsent(prefix, k -> new LinkedList<>()).addFirst(uri); } /* * Removes the URI at the top of the stack of URIs to which the given * prefix is mapped. * * @param prefix The prefix whose stack of URIs is to be popped */ public void popPrefixMapping(String prefix) { Deque<String> stack = xmlPrefixMapper.get(prefix); stack.removeFirst(); } /* * Returns the URI to which the given prefix maps. * * @param prefix The prefix whose URI is sought * * @return The URI to which the given prefix maps */ public String getURI(String prefix) { String uri = null; Deque<String> stack = xmlPrefixMapper.get(prefix); if (stack == null || stack.size() == 0) { uri = jspPrefixMapper.get(prefix); } else { uri = stack.getFirst(); } return uri; } /* Page/Tag directive attributes */ /* * language */ public void setLanguage(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if (!"java".equalsIgnoreCase(value)) { if (pagedir) { err.jspError(n, "jsp.error.page.language.nonjava"); } else { err.jspError(n, "jsp.error.tag.language.nonjava"); } } language = value; } public String getLanguage(boolean useDefault) { return (language == null && useDefault ? defaultLanguage : language); } /* * extends */ public void setExtends(String value) { xtends = value; } /** * Gets the value of the 'extends' page directive attribute. * * @param useDefault TRUE if the default * (org.apache.jasper.runtime.HttpJspBase) should be returned if this * attribute has not been set, FALSE otherwise * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set and useDefault is TRUE */ public String getExtends(boolean useDefault) { return (xtends == null && useDefault ? defaultExtends : xtends); } /** * Gets the value of the 'extends' page directive attribute. * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set */ public String getExtends() { return getExtends(true); } /* * contentType */ public void setContentType(String value) { contentType = value; } public String getContentType() { return contentType; } /* * buffer */ public void setBufferValue(String value, Node n, ErrorDispatcher err) throws JasperException { if ("none".equalsIgnoreCase(value)) { buffer = 0; } else { if (value == null || !value.endsWith("kb")) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } try { @SuppressWarnings("null") // value can't be null here int k = Integer.parseInt(value.substring(0, value.length()-2)); buffer = k * 1024; } catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } } bufferValue = value; } public String getBufferValue() { return bufferValue; } public int getBuffer() { return buffer; } /* * session */ public void setSession(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isSession = true; } else if ("false".equalsIgnoreCase(value)) { isSession = false; } else { err.jspError(n, "jsp.error.page.invalid.session"); } session = value; } public String getSession() { return session; } public boolean isSession() { return isSession; } /* * autoFlush */ public void setAutoFlush(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isAutoFlush = true; } else if ("false".equalsIgnoreCase(value)) { isAutoFlush = false; } else { err.jspError(n, "jsp.error.autoFlush.invalid"); } autoFlush = value; } public String getAutoFlush() { return autoFlush; } public boolean isAutoFlush() { return isAutoFlush; } /* * info */ public void setInfo(String value) { info = value; } public String getInfo() { return info; } /* * errorPage */ public void setErrorPage(String value) { errorPage = value; } public String getErrorPage() { return errorPage; } /* * isErrorPage <SUF>*/ public void setIsErrorPage(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) { isErrorPage = true; } else if ("false".equalsIgnoreCase(value)) { isErrorPage = false; } else { err.jspError(n, "jsp.error.page.invalid.iserrorpage"); } isErrorPageValue = value; } public String getIsErrorPage() { return isErrorPageValue; } public boolean isErrorPage() { return isErrorPage; } /* * isELIgnored */ public void setIsELIgnored(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { isELIgnored = true; } else if ("false".equalsIgnoreCase(value)) { isELIgnored = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.iselignored"); } else { err.jspError(n, "jsp.error.tag.invalid.iselignored"); } } isELIgnoredValue = value; } /* * errorOnELNotFound */ public void setErrorOnELNotFound(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { errorOnELNotFound = true; } else if ("false".equalsIgnoreCase(value)) { errorOnELNotFound = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.errorOnELNotFound"); } else { err.jspError(n, "jsp.error.tag.invalid.errorOnELNotFound"); } } errorOnELNotFoundValue = value; } /* * deferredSyntaxAllowedAsLiteral */ public void setDeferredSyntaxAllowedAsLiteral(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { deferredSyntaxAllowedAsLiteral = true; } else if ("false".equalsIgnoreCase(value)) { deferredSyntaxAllowedAsLiteral = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.deferredsyntaxallowedasliteral"); } else { err.jspError(n, "jsp.error.tag.invalid.deferredsyntaxallowedasliteral"); } } deferredSyntaxAllowedAsLiteralValue = value; } /* * trimDirectiveWhitespaces */ public void setTrimDirectiveWhitespaces(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) { trimDirectiveWhitespaces = true; } else if ("false".equalsIgnoreCase(value)) { trimDirectiveWhitespaces = false; } else { if (pagedir) { err.jspError(n, "jsp.error.page.invalid.trimdirectivewhitespaces"); } else { err.jspError(n, "jsp.error.tag.invalid.trimdirectivewhitespaces"); } } trimDirectiveWhitespacesValue = value; } public void setELIgnored(boolean s) { isELIgnored = s; } public String getIsELIgnored() { return isELIgnoredValue; } public boolean isELIgnored() { return isELIgnored; } public void setErrorOnELNotFound(boolean s) { errorOnELNotFound = s; } public String getErrorOnELNotFound() { return errorOnELNotFoundValue; } public boolean isErrorOnELNotFound() { return errorOnELNotFound; } public void putNonCustomTagPrefix(String prefix, Mark where) { nonCustomTagPrefixMap.put(prefix, where); } public Mark getNonCustomTagPrefix(String prefix) { return nonCustomTagPrefixMap.get(prefix); } public String getDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteralValue; } public boolean isDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteral; } public void setDeferredSyntaxAllowedAsLiteral(boolean isELDeferred) { this.deferredSyntaxAllowedAsLiteral = isELDeferred; } public ExpressionFactory getExpressionFactory() { return expressionFactory; } public String getTrimDirectiveWhitespaces() { return trimDirectiveWhitespacesValue; } public boolean isTrimDirectiveWhitespaces() { return trimDirectiveWhitespaces; } public void setTrimDirectiveWhitespaces(boolean trimDirectiveWhitespaces) { this.trimDirectiveWhitespaces = trimDirectiveWhitespaces; } public Set<String> getVarInfoNames() { return varInfoNames; } public boolean isErrorOnUndeclaredNamespace() { return errorOnUndeclaredNamespace; } public void setErrorOnUndeclaredNamespace( boolean errorOnUndeclaredNamespace) { this.errorOnUndeclaredNamespace = errorOnUndeclaredNamespace; } }
1602_1
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
// in constructor images declareren, afstand tussen magazijnvakken declareren.
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor<SUF> try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_2
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
// afstandx en y staat voor de afstand tussen magazijncoordinaten,
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en<SUF> //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_3
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//bv: tussen vakje 3 en 4 zitten 100 x coords
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen<SUF> for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_4
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//route tekenen als drawroute == true, if not, overslaan
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen<SUF> if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_5
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//als drawroute == true, dan word(en) ook de producten en robot getekend
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute<SUF> drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_6
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//drawrobotimage aan de hand van een gegeven counter.
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan<SUF> private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_7
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
// methode om resultaat van de gegenereerde route door te geven aan deze klasse.
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om<SUF> public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_8
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen.
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen<SUF> //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1602_9
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,728
//aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn.
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de<SUF> public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
1604_2
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Deze klasse wordt gebruikt om de database te benaderen. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt<SUF>*/ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_3
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe<SUF>*/ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_4
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst<SUF>*/ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_5
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel<SUF>*/ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_6
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst<SUF>*/ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_7
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst<SUF>*/ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_8
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel<SUF>*/ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_9
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt<SUF>*/ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_10
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt<SUF>*/ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_12
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal();
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp<SUF> // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_13
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// IOnderdeel on = ond.get(fr.getOnderdeelCode()-1);
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on<SUF> // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_14
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// if (!db.VeranderOnderdeel(on.getCode(), on)) {
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(),<SUF> // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_15
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel");
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is<SUF> // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_16
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er<SUF>*/ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_17
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er<SUF>*/ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_18
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De<SUF>*/ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_19
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De<SUF>*/ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_21
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving,<SUF>*/ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_22
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
/** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt<SUF>*/ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_25
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// IOnderdeel on = ond.get(fr[0]);
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on<SUF> // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_26
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// if (!db.VeranderOnderdeel(on.getCode(), on)) {
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(),<SUF> // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1604_27
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
niekert/AIDaS-PTS-SEI
src/main/java/Magazijn/Beheer.java
5,045
// System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel");
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Magazijn; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import magazijnapplicatie.*; /** * * @author Rob Maas */ public class Beheer implements IMagazijn,APInterface { //Variabelen /** * Deze klasse wordt gebruikt om de database te benaderen. */ private DatabaseConnectie db; //Constructor /** * MaaktEEE een nieuwe databaseConnectie-klasse aan. Deze geeft toegang tot de methoden die nodig zijn om de database te benaderen. */ public Beheer() { try { db = new DatabaseConnectie(); } catch (Exception ex) { Logger.getLogger(Beheer.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="Methoden"> //<editor-fold desc="Opvraag"> /** * Haalt een lijst op van alle onderdelen uit de database. * @return Een lijst van IOnderdeel objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IOnderdeel> GetOnderdelen() { ArrayList<IOnderdeel> ond = new ArrayList<IOnderdeel>(); try { ond = db.GetOnderdelen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de onderdelen. " + e.getMessage()); } return ond; } /** * Haalt een onderdeel op uit de database. * @param code De code van het op te halen onderdeel. * @return Het bijbehorende IOnderdeel-object (Interface). */ public IOnderdeel GetOnderdeel(int code) { IOnderdeel ond = null; try { ond = db.GetOnderdeel(code); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return ond; } /** * Haalt een lijst op van alle klanten uit de database. * @return Een lijst van IKlant objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IKlant> GetKlanten() { ArrayList<IKlant> klanten = null; try { klanten = db.GetKlanten(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return klanten; } /** * Haalt een lijst op van alle facturen uit de database. * @return Een lijst van IFactuur objecten (Interface). * Als er iets fout gegaan is wordt een lege ArrayList gereturneerd. * (Let dan wel op, want het kan ook zijn dat de query geen row teruggeeft!) */ public ArrayList<IFactuur> GetFacturen() { ArrayList<IFactuur> facturen = null; try { facturen = db.GetFacturen(); } catch (Exception e) { System.out.println("Er is iets fout gegaan bij het ophalen van de klanten. " + e.getMessage()); } return facturen; } //</editor-fold> //<editor-fold desc="ToeVoeg-Methoden"> /** * Creert een Onderdeel object en deze wordt toegevoegd in de database. * Als het aantal of de prijs minder dan 0 is, de omschrijving null of gelijk is aan een lege string wordt de actie onderbroken: Returns -1. * @param omschrijving De omschrijving van het Onderdeel (zoals deze in de database wordt opgeslagen). * @param aantal Het x aantal keer dat het product in het magazijn wordt toegevoegd. * @param prijs De prijs van het Onderdeel (zoals deze in de database wordt opgeslagen). * @return True als het object correct is toegevoegd, false als dit niet het geval is. */ public int VoegOnderdeelToe(String omschrijving, int aantal, int prijs) { if (aantal < 0 || prijs < 0 || omschrijving == null || omschrijving.equals("")) { return -1; } try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); int highest = 0; for (IOnderdeel ond : onderdelen) { if (ond.getCode() > highest) { highest = ond.getCode(); } } IOnderdeel ond = new Onderdeel((highest + 1), omschrijving, aantal, prijs); if (db.VoegOnderdeelToe(ond)) { return ond.getCode(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van het onderdeel. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt klantnummer en voegt de nieuwe klant toe aan de database. * Als de parameters gelijk zijn aan null of gelijk zijn aan een lege string wordt de actie afgebroken: Returns -1. * @param naam De naam van de Klant (Zoals deze in de database wordt opgeslagen). * @param adres Het aders van de Klant (Zoals deze in de database wordt opgeslagen). * @return Het klantnummer als de klant correct is toegevoegd, returneert -1 als dit niet het geval is. */ public int VoegKlantToe(String naam, String adres) { if (naam.equals("") || naam == null || adres == null || adres.equals("")) { return -1; } try { ArrayList<IKlant> klanten = db.GetKlanten(); int highest = 0; for (IKlant kl : klanten) { if (kl.getId() > highest) { highest = kl.getId(); } } IKlant klant = new Klant((highest + 1), naam, adres); if (db.VoegKlantToe(klant)) { return klant.getId(); } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het toevoegen van de klant. " + e.getMessage()); } return -1; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe aan de database als de variabelen kloppen. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: Array van int[], waarvan int[0] de onderdeelcode is en int[1] het aantal te bestellen. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int VoegFactuurToe(int klantId, ArrayList<IFactuurRegel> onderdelen) { try { ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (IFactuurRegel fr : onderdelen) { if (fr.getOnderdeelCode() < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr.getOnderdeelCode()) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr.getAantal()) { return -1; } } else { return -1; } } for(IFactuurRegel fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr.getOnderdeelCode()){ int temp = ondr.getAantal() - fr.getAantal(); on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // // for (IFactuurRegel fr : onderdelen) { // int temp = ond.get(fr.getOnderdeelCode()-1).getAantal() - fr.getAantal(); // IOnderdeel on = ond.get(fr.getOnderdeelCode()-1); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) +1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.VoegFactuurToe(new Factuur(date, klantId, (factuurNr+1), onderdelen))) { return factuurNr; } } catch (Exception e) { e.printStackTrace(); System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //<editor-fold desc="Verwijder-Methoden"> /** * Controleert of er een klant is met ingevoerde klantID, zoja wordt deze verwijdert. * @param klantId Het ID van de klant die verwijdert moet worden. * @return True als de klant correct verwijdert is. False als dit niet het geval is. */ public boolean VerwijderKlant(int klantId) { if (klantId >= 0) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klantId) { if (db.VerwijderKlant(kl.getId())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van de klant. " + e.getMessage()); return false; } } return false; } /** * Controleert of er een onderdeel bestaat met ingevoerde OnderdeelCode, zoja wordt deze verwijdert. * @param onderdeelCode De Code die hoort bij het onderdeel wat verwijdert moet worden. * @return True als het onderdeel correct verwijdert is. False als dit niet geval is. */ public boolean VerwijderOnderdeel(int onderdeelCode) { if (onderdeelCode >= 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeelCode) { if (db.VerwijderOnderdeel(odd.getCode())) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het verwijderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="Verander-Methoden"> /** * (LET OP! De KlantID kan niet worden aangepast, enkel de naam en het adres!!) * Controleert of het ingevoerde IKlant-object correct is. Als dit zo is worden de veranderen aangebracht in de database. * Zowel de naam als het adres moet ingevoerd worden, als deze niet veranderd hoeven worden moeten de oude waardes ingevoerd worden. * @param klant Het IKlant-object met ingevoerde nieuwe waardes. * @return True als de Klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderKlant(IKlant klant) { if (klant != null && klant.getId() > 0 && klant.getAdres() != null && !klant.getAdres().equals("") && klant.getNaam() != null && !klant.getNaam().equals("")) { try { ArrayList<IKlant> klanten = db.GetKlanten(); for (IKlant kl : klanten) { if (kl.getId() == klant.getId()) { if (db.VeranderKlant(klant.getId(), klant)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van de klant. " + e.getMessage()); return false; } } return false; } /** * (LET OP! De onderdeelCode kan niet worden aangepast, enkel de omschrijving het aantal en de prijs!) * Controleert of het ingevoerde IOnderdeel-obejct correct is. Als dit zo is worden de veranderingen aangebracht in de database. * De omschrijving, het aantal en de prijs moeten ingevoerd worden, als er niets veranderd hoeft te worden, voer dan de oude waardes in. * @param onderdeel Het IOnderdeel-object met ingevoerde nieuwe waardes. * @return True als de klantgegevens correct veranderd zijn, anders false. */ public boolean VeranderOnderdeel(IOnderdeel onderdeel) { if (onderdeel.getCode() > 0 && onderdeel.getOmschrijving() != null && !onderdeel.getOmschrijving().equals("") && onderdeel.getAantal() > 0 && onderdeel.getPrijs() > 0) { try { ArrayList<IOnderdeel> onderdelen = db.GetOnderdelen(); for (IOnderdeel odd : onderdelen) { if (odd.getCode() == onderdeel.getCode()) { if (db.VeranderOnderdeel(onderdeel.getCode(), onderdeel)) { return true; } } } } catch (Exception e) { System.out.println("Er is iets fout gegaan met het veranderen van het onderdeel. " + e.getMessage()); return false; } } return false; } //</editor-fold> //<editor-fold desc="API-Interface Methoden"> /** * Haalt de omschrijving, prijs en het aantal van een onderdeel op. * * Deze methode wordt gebruikt door de APInterface. * @param onderdeelCode De code van het onderdeel waarvan de informatie moet worden opgehaald. * @return Een Object[] met de volgende waardes: * [0] String: De omschrijving van het onderdeel. * [1] int: De prijs van het onderdeel in centen. * [2] int: Het aantal van het onderdeel. */ public Object[] VraagOnderdeelOp(int onderdeelCode){ Object[] temp = null; try{ temp = db.VraagOnderdeelOp(onderdeelCode); } catch(Exception e){ System.out.println("Er is iets fout gegaan bij het ophalen van het onderdeel. " + e.getMessage()); } return temp; } /** * Zoekt een geschikt nieuw factuurnummer en voegt de factuur toe als de variabelen kloppen, als de variabelen niet kloppen wordt -1 gereturneerd. * Ook wordt het aantal van de betreffende onderdelen in de database verlaagt met het aantal te bestellen van dat onderdeel, * als er niet genoeg onderdelen over zijn wordt ook -1 gereturneerd. * @param klantId Het ID van de klant die de factuur aanvraagt. * @param onderdelen Lijst met onderdelen die besteld worden: * De ArrayList heeft int[] objecten, en elke int[] staat voor een onderdeel: * int[0]: De code van het onderdeel. * int[1]: Het aantal van dat onderdeel dat besteld moet worden. * @return Als de factuur correct wordt toegevoegd wordt het factuurnummer gereturneerd, anders wordt -1 gereturneerd. */ public int FactuurToeVoegen(int klantId, ArrayList<int[]> onderdelen) { try{ ArrayList<IFactuur> facturen = db.GetFacturen(); int factuurNr = 0; for (IFactuur fc : facturen) { if (fc.getFactuurId() > factuurNr) { factuurNr = fc.getFactuurId(); } } ArrayList<IKlant> klanten = db.GetKlanten(); IKlant klant = null; for (int i = 0; i < klanten.size(); i++) { if (klanten.get(i).getId() == klantId) { klant = klanten.get(i); } } if (klant == null) { return -1; } ArrayList<IOnderdeel> ond = db.GetOnderdelen(); for (int[] fr : onderdelen) { if (fr[0] < 1) { return -1; } IOnderdeel odd = null; for (int i = 0; i < ond.size(); i++) { if (ond.get(i).getCode() == fr[0]) { odd = ond.get(i); } } if (odd != null) { if (odd.getAantal() < fr[1]) { return -1; } } else { return -1; } } for(int[] fr: onderdelen){ IOnderdeel on = null; for(IOnderdeel ondr:ond){ if(ondr.getCode() == fr[0]){ int temp = ondr.getAantal() - fr[1]; on = new Onderdeel(ondr.getCode(),ondr.getOmschrijving(),temp,ondr.getPrijs()); } } if (!db.VeranderOnderdeel(on.getCode(), on)) { System.out.println("Er is iets fout gegaan bij db.VeranderOnderdeel"); } } // for (int[] fr : onderdelen) { // int temp = ond.get(fr[0]).getAantal() - fr[1]; // IOnderdeel on = ond.get(fr[0]); // on.setAantal(temp); // if (!db.VeranderOnderdeel(on.getCode(), on)) { // System.out.println("Er is<SUF> // } // } Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); String date = Integer.toString(day) + "-" + Integer.toString(month) + "-" + Integer.toString(year); if (db.FactuurToevoegen(factuurNr+1, klantId, date, onderdelen)) { return factuurNr; } } catch(Exception e){ System.out.println("Er is iets fout gegaan met het toevoegen van de factuur. " + e.getMessage()); } return -1; } //</editor-fold> //</editor-fold> }
1607_0
package gearth.ui.buttons; import javafx.event.EventHandler; import javafx.scene.Cursor; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import java.io.File; public class BoxButton extends StackPane { private ImageView imageView; private Image image; private Image imageOnHover; private boolean isVisible; //paths zijn relatief aan deze classpath public BoxButton(String imageName, String imageOnHoverName) { this.image = new Image(getClass().getResourceAsStream("files/" + imageName)); this.imageOnHover = new Image(getClass().getResourceAsStream("files/" + imageOnHoverName)); this.imageView = new ImageView(); setCursor(Cursor.DEFAULT); getChildren().add(imageView); setOnMouseEntered(onMouseHover); setOnMouseExited(onMouseHoverDone); } public void show() { imageView.setImage(image); isVisible = true; } public void dispose() { imageView.setImage(null); isVisible = false; } private EventHandler<MouseEvent> onMouseHover = t -> { if (isVisible) { imageView.setImage(imageOnHover); } }; private EventHandler<MouseEvent> onMouseHoverDone = t -> { if (isVisible) { imageView.setImage(image); } }; }
sirjonasxx/G-Earth
G-Earth/src/main/java/gearth/ui/buttons/BoxButton.java
357
//paths zijn relatief aan deze classpath
line_comment
nl
package gearth.ui.buttons; import javafx.event.EventHandler; import javafx.scene.Cursor; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import java.io.File; public class BoxButton extends StackPane { private ImageView imageView; private Image image; private Image imageOnHover; private boolean isVisible; //paths zijn<SUF> public BoxButton(String imageName, String imageOnHoverName) { this.image = new Image(getClass().getResourceAsStream("files/" + imageName)); this.imageOnHover = new Image(getClass().getResourceAsStream("files/" + imageOnHoverName)); this.imageView = new ImageView(); setCursor(Cursor.DEFAULT); getChildren().add(imageView); setOnMouseEntered(onMouseHover); setOnMouseExited(onMouseHoverDone); } public void show() { imageView.setImage(image); isVisible = true; } public void dispose() { imageView.setImage(null); isVisible = false; } private EventHandler<MouseEvent> onMouseHover = t -> { if (isVisible) { imageView.setImage(imageOnHover); } }; private EventHandler<MouseEvent> onMouseHoverDone = t -> { if (isVisible) { imageView.setImage(image); } }; }
1610_7
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012-2017 [email protected] XOWA is licensed under the terms of the General Public License (GPL) Version 3, or alternatively under the terms of the Apache License Version 2.0. You may use XOWA according to either of these licenses as is most appropriate for your project on a case-by-case basis. The terms of each license can be found in the source code repository: GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt */ package gplx.xowa.files.repos; import gplx.*; import gplx.xowa.*; import gplx.xowa.files.*; import gplx.xowa.files.xfers.*; import gplx.xowa.wikis.domains.*; import gplx.xowa.parsers.utils.*; import gplx.xowa.wikis.tdbs.metas.*; public class Xowe_repo_mgr implements Xow_repo_mgr, Gfo_invk { private Xofw_file_finder_rslt tmp_rslt = new Xofw_file_finder_rslt(); private Xowe_wiki wiki; private final List_adp repos = List_adp_.New(); public Xowe_repo_mgr(Xowe_wiki wiki) { this.wiki = wiki; Xoae_app app = wiki.Appe(); xfer_mgr = new Xof_xfer_mgr(app.File_mgr(), app.Wmf_mgr()); page_finder = new Xofw_wiki_wkr_base(wiki, app.Wiki_mgr()); } public Xof_xfer_mgr Xfer_mgr() {return xfer_mgr;} private Xof_xfer_mgr xfer_mgr; public Xowe_repo_mgr Page_finder_(Xofw_wiki_finder v) {page_finder = v; return this;} private Xofw_wiki_finder page_finder; public int Repos_len() {return repos.Count();} public Xof_repo_pair Repos_get_by_wiki(byte[] wiki) { int len = repos.Count(); for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (Bry_.Eq(wiki, pair.Wiki_domain())) return pair; } return null; } public void Repos_clear() {repos.Clear();} public void Clone(Xowe_repo_mgr src) { this.Repos_clear(); int len = src.Repos_len(); for (int i = 0; i < len; ++i) { Xof_repo_pair repo_pair = src.Repos_get_at(i); this.Add_repo(repo_pair.Src().Key(), repo_pair.Trg().Key()); } } public Xof_repo_pair Repos_get_at(int i) {return (Xof_repo_pair)repos.Get_at(i);} private Xof_repo_pair Repos_get_by_id(int id) { int len = repos.Count(); for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (pair.Id() == id) return pair; } return null; } public Xof_repo_itm Get_trg_by_id_or_null(int id, byte[] lnki_ttl, byte[] page_url) { Xof_repo_pair pair = Repos_get_by_id(id); if (pair == null) { Xoa_app_.Usr_dlg().Warn_many("", "", "repo_mgr.invalid_repo: repo=~{0} lnki_ttl=~{1} page_url=~{2}", id, lnki_ttl, page_url); return null; } else return pair.Trg(); } public Xof_repo_itm Get_src_by_id_or_null(int id, byte[] lnki_ttl, byte[] page_url) { Xof_repo_pair pair = Repos_get_by_id(id); if (pair == null) { Xoa_app_.Usr_dlg().Warn_many("", "", "repo_mgr.invalid_repo: repo=~{0} lnki_ttl=~{1} page_url=~{2}", id, lnki_ttl, page_url); return null; } else return pair.Src(); } public Xof_repo_itm Get_trg_by_tid_or_null(byte[] tid) { return null; } public Xof_repo_pair[] Repos_ary() {if (repos_ary == null) repos_ary = (Xof_repo_pair[])repos.To_ary(Xof_repo_pair.class); return repos_ary;} private Xof_repo_pair[] repos_ary; public boolean Xfer_by_meta(Xof_xfer_itm xfer_itm, Xof_xfer_queue queue) { byte[] ttl = xfer_itm.Lnki_ttl(); Xof_meta_itm meta_itm = xfer_itm.Dbmeta_itm(); boolean chk_all = false; byte[] src_wiki_key = wiki.Domain_bry(); if (meta_itm.State_new()) { byte rslt = Xfer_by_meta__find_file(ttl, meta_itm, wiki.Domain_bry()); switch (rslt) { case Xof_meta_itm.Tid_null: xfer_itm.Orig_repo_id_(0); chk_all = true; break; // NOTE: src_wiki_key becomes wiki.Key_bry() for sake of simplicity case Xof_meta_itm.Tid_main: xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); break; case Xof_meta_itm.Tid_ptr: src_wiki_key = Xfer_by_meta__find_main_ptr(meta_itm, xfer_itm); break; case Xof_meta_itm.Tid_vrtl: src_wiki_key = Xfer_by_meta__find_main_vrtl(meta_itm, xfer_itm); break; } } else { Xof_repo_itm src_repo = meta_itm.Repo_itm(wiki); src_wiki_key = src_repo.Wiki_domain(); xfer_itm.Orig_repo_id_(meta_itm.Vrtl_repo()); // NOTE: set trg_repo_idx b/c xfer_mgr will always set meta_itm.Vrtl_repo() with trg_repo_idx } if (meta_itm.Ptr_ttl_exists()) xfer_itm.Orig_ttl_and_redirect_(meta_itm.Ttl(), meta_itm.Ptr_ttl()); boolean main_exists_unknown = src_wiki_key == null; // WORKAROUND/HACK: SEE:NOTE_1:reset_main_exists boolean rv = Xfer_by_meta__exec(chk_all, xfer_itm, meta_itm, src_wiki_key, queue, false); if (!rv && (!chk_all && !main_exists_unknown)) { // xfer failed even with page found in wiki; try again, but chk all rv = Xfer_by_meta__exec(true, xfer_itm, meta_itm, src_wiki_key, queue, true); } return rv; } byte[] Xfer_by_meta__find_main_ptr(Xof_meta_itm meta_itm, Xof_xfer_itm xfer_itm) { byte[] redirect = meta_itm.Ptr_ttl(); int redirect_tries = 0; byte[] md5 = Xof_file_wkr_.Md5(redirect); while (true) { boolean found = page_finder.Locate(tmp_rslt, repos, redirect); if (!found) return null; Xowe_wiki trg_wiki = wiki; int repo_idx = tmp_rslt.Repo_idx(); byte[] trg_wiki_key = Bry_.Empty; if (repo_idx != Xof_meta_itm.Repo_unknown) { trg_wiki_key = wiki.File_mgr().Repo_mgr().Repos_get_at(repo_idx).Wiki_domain(); trg_wiki = wiki.Appe().Wiki_mgr().Get_by_or_make(trg_wiki_key); } Xof_meta_itm redirect_meta = trg_wiki.File_mgr().Dbmeta_mgr().Get_itm_or_new(redirect, md5); if (tmp_rslt.Redirect() == Xop_redirect_mgr.Redirect_null_bry) { if (redirect_meta.State_new()) { if (repo_idx == Xof_meta_itm.Repo_unknown) { // meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); } else { if (!Bry_.Eq(trg_wiki_key, wiki.Domain_bry())) { // meta_itm.Vrtl_repo_(tmp_rslt.Repo_idx()); xfer_itm.Orig_repo_id_(tmp_rslt.Repo_idx()); } else { // meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); } } } return trg_wiki_key; } redirect = tmp_rslt.Redirect(); if (++redirect_tries > Xop_redirect_mgr.Redirect_max_allowed) return null; } } byte[] Xfer_by_meta__find_main_vrtl(Xof_meta_itm meta_itm, Xof_xfer_itm xfer_itm) { int repo_idx = meta_itm.Vrtl_repo(); if (repo_idx == Xof_meta_itm.Repo_unknown) return null;; Xof_repo_itm trg_repo = wiki.File_mgr().Repo_mgr().Repos_get_at(repo_idx).Trg(); xfer_itm.Orig_repo_id_(repo_idx); return trg_repo.Wiki_domain(); } boolean Xfer_by_meta__exec(boolean chk_all, Xof_xfer_itm xfer_itm, Xof_meta_itm meta_itm, byte[] main_wiki_key, Xof_xfer_queue queue, boolean second_chance) { int repos_len = repos.Count(); for (int i = 0; i < repos_len; i++) { // iterate over all repo pairs Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); Xof_repo_itm pair_src = pair.Src(); boolean main_wiki_key_is_pair_src = Bry_.Eq(main_wiki_key, pair_src.Wiki_domain()); if ( (chk_all && !main_wiki_key_is_pair_src) // only do chk_all if main_wiki is not pair_src; note that chk_all will only be called in two ways (1) with main_wiki_key as null; (2) with main_key_as val || (!chk_all && main_wiki_key_is_pair_src)) { // pair.Src.Wiki == main.Wiki; note that there can be multiple pairs with same src; EX: have 2 pairs for commons: one for file and another for http xfer_mgr.Atrs_by_itm(xfer_itm, pair_src, pair.Trg()); boolean make = xfer_mgr.Make_file(wiki); if (make) { xfer_itm.Trg_repo_itm_(pair.Trg()); if (second_chance && xfer_itm.Dbmeta_itm().Vrtl_repo() == 0) // second_chance and item found; change vrtl_repo from commons back to same; EX: tarball and [[Image:Rembrandt De aartsengel verlaat Tobias en zijn gezin. 1637.jpg|120px]] xfer_itm.Dbmeta_itm().Vrtl_repo_(Xof_meta_itm.Repo_same); return true; // file was made; return; if not continue looking at other repos } } } return false; } public Xofw_file_finder_rslt Page_finder_locate(byte[] ttl_bry) {page_finder.Locate(tmp_rslt, repos, ttl_bry); return tmp_rslt;} byte Xfer_by_meta__find_file(byte[] ttl_bry, Xof_meta_itm meta_itm, byte[] cur_wiki_key) { byte new_tid = Byte_.Max_value_127; boolean found = page_finder.Locate(tmp_rslt, repos, ttl_bry); if (found) { if (Bry_.Eq(cur_wiki_key, tmp_rslt.Repo_wiki_key())) { // itm is in same repo as cur wiki new_tid = Xof_meta_itm.Tid_main; byte[] redirect = tmp_rslt.Redirect(); if (redirect != Xop_redirect_mgr.Redirect_null_bry) { // redirect found meta_itm.Ptr_ttl_(redirect); } meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); } else { // itm is in diff repo new_tid = Xof_meta_itm.Tid_vrtl; meta_itm.Vrtl_repo_(tmp_rslt.Repo_idx()); meta_itm.Ptr_ttl_(tmp_rslt.Redirect()); } } else { // itm not found; has to be vrtl, but mark repo as unknown meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_unknown); } return new_tid; } public Object Invk(GfsCtx ctx, int ikey, String k, GfoMsg m) { if (ctx.Match(k, Invk_add)) return Add_repo(m.ReadBry("src"), m.ReadBry("trg")); else if (ctx.Match(k, Invk_clear)) {repos.Clear(); repos_ary = null;} // reset repos_ary variable else return Gfo_invk_.Rv_unhandled; return this; } private static final String Invk_add = "add", Invk_clear = "clear"; public Xof_repo_pair Add_repo(byte[] src_repo_key, byte[] trg_repo_key) { repos_ary = null; // reset repos_ary variable Xoa_repo_mgr repo_mgr = wiki.Appe().File_mgr().Repo_mgr(); Xof_repo_itm src_repo = repo_mgr.Get_by(src_repo_key), trg_repo = repo_mgr.Get_by(trg_repo_key); byte[] src_wiki_key = src_repo.Wiki_domain(), trg_wiki_key = trg_repo.Wiki_domain(); if (!Bry_.Eq(src_wiki_key, trg_wiki_key) && !Bry_.Eq(src_wiki_key, Xow_domain_tid_.Bry__home)) throw Err_.new_wo_type("wiki keys do not match", "src", String_.new_u8(src_wiki_key), "trg", String_.new_u8(trg_wiki_key)); Xof_repo_pair pair = new Xof_repo_pair((byte)repos.Count(), src_wiki_key, src_repo, trg_repo); repos.Add(pair); return pair; } public boolean Xfer_file(Xof_xfer_itm file) { int repo_idx = file.Orig_repo_id(); boolean wiki_is_unknown = repo_idx == Xof_meta_itm.Repo_unknown; boolean make_pass = false; int len = repos.Count(); if (!wiki_is_unknown) make_pass = Xfer_file_exec(file, this.Repos_get_at(repo_idx), repo_idx); if (make_pass) return true; for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (i != repo_idx) { // try other wikis file.Dbmeta_itm().Orig_exists_(Xof_meta_itm.Exists_unknown); // always reset orig exists; this may have been flagged to missing above and should be cleared make_pass = Xfer_file_exec(file, pair, i); if (make_pass) break; } } return make_pass; } private boolean Xfer_file_exec(Xof_xfer_itm file, Xof_repo_pair pair, int repo_idx) { xfer_mgr.Atrs_by_itm(file, pair.Src(), pair.Trg()); Xof_meta_itm meta_itm = xfer_mgr.Dbmeta_itm(); boolean rv = xfer_mgr.Make_file(wiki); if (rv) { meta_itm.Vrtl_repo_(repo_idx); // update repo_idx to whatever is found } return rv; } } /* NOTE_1:reset_main_exists this is primarily for Img_missing_wiki_1 and [[Image:Alcott-L.jpg|thumb|right|Louisa May Alcott]] first some details: . file pages exist in both en_wiki and in commons_wiki; w:File:Alcott-L.jpg; c:File:Alcott-L.jpg . images are slightly different (w: is darker than c:) . c was recently updated to redirect to File:Louisa May Alcott (1881 illustration).jpg the actual effect: . [[Image:Alcott-L.jpg|thumb|right|Louisa May Alcott]] in en.wikipedia should pull the w: one (not the c:) one . this behavior seems contrary to all other wiki behavior where c: is given primacy over w: .. EX: [[File:Tanks of WWI.ogg|thumb|thumbtime=12|alt=Primitive]] exists in both en_wiki and in commons, but the file only exists in commons . moreover this page has a special note about the image deliberately remainining in en_wiki the workaround/hack (described via intended sequence): 1: commons is defined as first repo_pair 2: image found in commons page (note that en_wiki is not checked for PERF reasons) 3: image is searched for in commons, but not found; note that both thumb and orig are missing 4: image will be searched for in en_wiki and found note that (4) however reuses the same meta which is marked as "not found" from the commons attempt . item will then have orig marked falsely as not-found one approach would be to create a new meta and send that into the chk_all function. this turned out to be problematic so, the workaround: if going into chk_all ...and orig was previous unknown ...but is now marked no then reset to unknown to give it a "clean" slate for the chk all in theory, the above statement seems fine, but it does seem hackish... */
gnosygnu/xowa
400_xowa/src/gplx/xowa/files/repos/Xowe_repo_mgr.java
4,904
// second_chance and item found; change vrtl_repo from commons back to same; EX: tarball and [[Image:Rembrandt De aartsengel verlaat Tobias en zijn gezin. 1637.jpg|120px]]
line_comment
nl
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012-2017 [email protected] XOWA is licensed under the terms of the General Public License (GPL) Version 3, or alternatively under the terms of the Apache License Version 2.0. You may use XOWA according to either of these licenses as is most appropriate for your project on a case-by-case basis. The terms of each license can be found in the source code repository: GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt */ package gplx.xowa.files.repos; import gplx.*; import gplx.xowa.*; import gplx.xowa.files.*; import gplx.xowa.files.xfers.*; import gplx.xowa.wikis.domains.*; import gplx.xowa.parsers.utils.*; import gplx.xowa.wikis.tdbs.metas.*; public class Xowe_repo_mgr implements Xow_repo_mgr, Gfo_invk { private Xofw_file_finder_rslt tmp_rslt = new Xofw_file_finder_rslt(); private Xowe_wiki wiki; private final List_adp repos = List_adp_.New(); public Xowe_repo_mgr(Xowe_wiki wiki) { this.wiki = wiki; Xoae_app app = wiki.Appe(); xfer_mgr = new Xof_xfer_mgr(app.File_mgr(), app.Wmf_mgr()); page_finder = new Xofw_wiki_wkr_base(wiki, app.Wiki_mgr()); } public Xof_xfer_mgr Xfer_mgr() {return xfer_mgr;} private Xof_xfer_mgr xfer_mgr; public Xowe_repo_mgr Page_finder_(Xofw_wiki_finder v) {page_finder = v; return this;} private Xofw_wiki_finder page_finder; public int Repos_len() {return repos.Count();} public Xof_repo_pair Repos_get_by_wiki(byte[] wiki) { int len = repos.Count(); for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (Bry_.Eq(wiki, pair.Wiki_domain())) return pair; } return null; } public void Repos_clear() {repos.Clear();} public void Clone(Xowe_repo_mgr src) { this.Repos_clear(); int len = src.Repos_len(); for (int i = 0; i < len; ++i) { Xof_repo_pair repo_pair = src.Repos_get_at(i); this.Add_repo(repo_pair.Src().Key(), repo_pair.Trg().Key()); } } public Xof_repo_pair Repos_get_at(int i) {return (Xof_repo_pair)repos.Get_at(i);} private Xof_repo_pair Repos_get_by_id(int id) { int len = repos.Count(); for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (pair.Id() == id) return pair; } return null; } public Xof_repo_itm Get_trg_by_id_or_null(int id, byte[] lnki_ttl, byte[] page_url) { Xof_repo_pair pair = Repos_get_by_id(id); if (pair == null) { Xoa_app_.Usr_dlg().Warn_many("", "", "repo_mgr.invalid_repo: repo=~{0} lnki_ttl=~{1} page_url=~{2}", id, lnki_ttl, page_url); return null; } else return pair.Trg(); } public Xof_repo_itm Get_src_by_id_or_null(int id, byte[] lnki_ttl, byte[] page_url) { Xof_repo_pair pair = Repos_get_by_id(id); if (pair == null) { Xoa_app_.Usr_dlg().Warn_many("", "", "repo_mgr.invalid_repo: repo=~{0} lnki_ttl=~{1} page_url=~{2}", id, lnki_ttl, page_url); return null; } else return pair.Src(); } public Xof_repo_itm Get_trg_by_tid_or_null(byte[] tid) { return null; } public Xof_repo_pair[] Repos_ary() {if (repos_ary == null) repos_ary = (Xof_repo_pair[])repos.To_ary(Xof_repo_pair.class); return repos_ary;} private Xof_repo_pair[] repos_ary; public boolean Xfer_by_meta(Xof_xfer_itm xfer_itm, Xof_xfer_queue queue) { byte[] ttl = xfer_itm.Lnki_ttl(); Xof_meta_itm meta_itm = xfer_itm.Dbmeta_itm(); boolean chk_all = false; byte[] src_wiki_key = wiki.Domain_bry(); if (meta_itm.State_new()) { byte rslt = Xfer_by_meta__find_file(ttl, meta_itm, wiki.Domain_bry()); switch (rslt) { case Xof_meta_itm.Tid_null: xfer_itm.Orig_repo_id_(0); chk_all = true; break; // NOTE: src_wiki_key becomes wiki.Key_bry() for sake of simplicity case Xof_meta_itm.Tid_main: xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); break; case Xof_meta_itm.Tid_ptr: src_wiki_key = Xfer_by_meta__find_main_ptr(meta_itm, xfer_itm); break; case Xof_meta_itm.Tid_vrtl: src_wiki_key = Xfer_by_meta__find_main_vrtl(meta_itm, xfer_itm); break; } } else { Xof_repo_itm src_repo = meta_itm.Repo_itm(wiki); src_wiki_key = src_repo.Wiki_domain(); xfer_itm.Orig_repo_id_(meta_itm.Vrtl_repo()); // NOTE: set trg_repo_idx b/c xfer_mgr will always set meta_itm.Vrtl_repo() with trg_repo_idx } if (meta_itm.Ptr_ttl_exists()) xfer_itm.Orig_ttl_and_redirect_(meta_itm.Ttl(), meta_itm.Ptr_ttl()); boolean main_exists_unknown = src_wiki_key == null; // WORKAROUND/HACK: SEE:NOTE_1:reset_main_exists boolean rv = Xfer_by_meta__exec(chk_all, xfer_itm, meta_itm, src_wiki_key, queue, false); if (!rv && (!chk_all && !main_exists_unknown)) { // xfer failed even with page found in wiki; try again, but chk all rv = Xfer_by_meta__exec(true, xfer_itm, meta_itm, src_wiki_key, queue, true); } return rv; } byte[] Xfer_by_meta__find_main_ptr(Xof_meta_itm meta_itm, Xof_xfer_itm xfer_itm) { byte[] redirect = meta_itm.Ptr_ttl(); int redirect_tries = 0; byte[] md5 = Xof_file_wkr_.Md5(redirect); while (true) { boolean found = page_finder.Locate(tmp_rslt, repos, redirect); if (!found) return null; Xowe_wiki trg_wiki = wiki; int repo_idx = tmp_rslt.Repo_idx(); byte[] trg_wiki_key = Bry_.Empty; if (repo_idx != Xof_meta_itm.Repo_unknown) { trg_wiki_key = wiki.File_mgr().Repo_mgr().Repos_get_at(repo_idx).Wiki_domain(); trg_wiki = wiki.Appe().Wiki_mgr().Get_by_or_make(trg_wiki_key); } Xof_meta_itm redirect_meta = trg_wiki.File_mgr().Dbmeta_mgr().Get_itm_or_new(redirect, md5); if (tmp_rslt.Redirect() == Xop_redirect_mgr.Redirect_null_bry) { if (redirect_meta.State_new()) { if (repo_idx == Xof_meta_itm.Repo_unknown) { // meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); } else { if (!Bry_.Eq(trg_wiki_key, wiki.Domain_bry())) { // meta_itm.Vrtl_repo_(tmp_rslt.Repo_idx()); xfer_itm.Orig_repo_id_(tmp_rslt.Repo_idx()); } else { // meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); xfer_itm.Orig_repo_id_(Xof_meta_itm.Repo_same); } } } return trg_wiki_key; } redirect = tmp_rslt.Redirect(); if (++redirect_tries > Xop_redirect_mgr.Redirect_max_allowed) return null; } } byte[] Xfer_by_meta__find_main_vrtl(Xof_meta_itm meta_itm, Xof_xfer_itm xfer_itm) { int repo_idx = meta_itm.Vrtl_repo(); if (repo_idx == Xof_meta_itm.Repo_unknown) return null;; Xof_repo_itm trg_repo = wiki.File_mgr().Repo_mgr().Repos_get_at(repo_idx).Trg(); xfer_itm.Orig_repo_id_(repo_idx); return trg_repo.Wiki_domain(); } boolean Xfer_by_meta__exec(boolean chk_all, Xof_xfer_itm xfer_itm, Xof_meta_itm meta_itm, byte[] main_wiki_key, Xof_xfer_queue queue, boolean second_chance) { int repos_len = repos.Count(); for (int i = 0; i < repos_len; i++) { // iterate over all repo pairs Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); Xof_repo_itm pair_src = pair.Src(); boolean main_wiki_key_is_pair_src = Bry_.Eq(main_wiki_key, pair_src.Wiki_domain()); if ( (chk_all && !main_wiki_key_is_pair_src) // only do chk_all if main_wiki is not pair_src; note that chk_all will only be called in two ways (1) with main_wiki_key as null; (2) with main_key_as val || (!chk_all && main_wiki_key_is_pair_src)) { // pair.Src.Wiki == main.Wiki; note that there can be multiple pairs with same src; EX: have 2 pairs for commons: one for file and another for http xfer_mgr.Atrs_by_itm(xfer_itm, pair_src, pair.Trg()); boolean make = xfer_mgr.Make_file(wiki); if (make) { xfer_itm.Trg_repo_itm_(pair.Trg()); if (second_chance && xfer_itm.Dbmeta_itm().Vrtl_repo() == 0) // second_chance and<SUF> xfer_itm.Dbmeta_itm().Vrtl_repo_(Xof_meta_itm.Repo_same); return true; // file was made; return; if not continue looking at other repos } } } return false; } public Xofw_file_finder_rslt Page_finder_locate(byte[] ttl_bry) {page_finder.Locate(tmp_rslt, repos, ttl_bry); return tmp_rslt;} byte Xfer_by_meta__find_file(byte[] ttl_bry, Xof_meta_itm meta_itm, byte[] cur_wiki_key) { byte new_tid = Byte_.Max_value_127; boolean found = page_finder.Locate(tmp_rslt, repos, ttl_bry); if (found) { if (Bry_.Eq(cur_wiki_key, tmp_rslt.Repo_wiki_key())) { // itm is in same repo as cur wiki new_tid = Xof_meta_itm.Tid_main; byte[] redirect = tmp_rslt.Redirect(); if (redirect != Xop_redirect_mgr.Redirect_null_bry) { // redirect found meta_itm.Ptr_ttl_(redirect); } meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_same); } else { // itm is in diff repo new_tid = Xof_meta_itm.Tid_vrtl; meta_itm.Vrtl_repo_(tmp_rslt.Repo_idx()); meta_itm.Ptr_ttl_(tmp_rslt.Redirect()); } } else { // itm not found; has to be vrtl, but mark repo as unknown meta_itm.Vrtl_repo_(Xof_meta_itm.Repo_unknown); } return new_tid; } public Object Invk(GfsCtx ctx, int ikey, String k, GfoMsg m) { if (ctx.Match(k, Invk_add)) return Add_repo(m.ReadBry("src"), m.ReadBry("trg")); else if (ctx.Match(k, Invk_clear)) {repos.Clear(); repos_ary = null;} // reset repos_ary variable else return Gfo_invk_.Rv_unhandled; return this; } private static final String Invk_add = "add", Invk_clear = "clear"; public Xof_repo_pair Add_repo(byte[] src_repo_key, byte[] trg_repo_key) { repos_ary = null; // reset repos_ary variable Xoa_repo_mgr repo_mgr = wiki.Appe().File_mgr().Repo_mgr(); Xof_repo_itm src_repo = repo_mgr.Get_by(src_repo_key), trg_repo = repo_mgr.Get_by(trg_repo_key); byte[] src_wiki_key = src_repo.Wiki_domain(), trg_wiki_key = trg_repo.Wiki_domain(); if (!Bry_.Eq(src_wiki_key, trg_wiki_key) && !Bry_.Eq(src_wiki_key, Xow_domain_tid_.Bry__home)) throw Err_.new_wo_type("wiki keys do not match", "src", String_.new_u8(src_wiki_key), "trg", String_.new_u8(trg_wiki_key)); Xof_repo_pair pair = new Xof_repo_pair((byte)repos.Count(), src_wiki_key, src_repo, trg_repo); repos.Add(pair); return pair; } public boolean Xfer_file(Xof_xfer_itm file) { int repo_idx = file.Orig_repo_id(); boolean wiki_is_unknown = repo_idx == Xof_meta_itm.Repo_unknown; boolean make_pass = false; int len = repos.Count(); if (!wiki_is_unknown) make_pass = Xfer_file_exec(file, this.Repos_get_at(repo_idx), repo_idx); if (make_pass) return true; for (int i = 0; i < len; i++) { Xof_repo_pair pair = (Xof_repo_pair)repos.Get_at(i); if (i != repo_idx) { // try other wikis file.Dbmeta_itm().Orig_exists_(Xof_meta_itm.Exists_unknown); // always reset orig exists; this may have been flagged to missing above and should be cleared make_pass = Xfer_file_exec(file, pair, i); if (make_pass) break; } } return make_pass; } private boolean Xfer_file_exec(Xof_xfer_itm file, Xof_repo_pair pair, int repo_idx) { xfer_mgr.Atrs_by_itm(file, pair.Src(), pair.Trg()); Xof_meta_itm meta_itm = xfer_mgr.Dbmeta_itm(); boolean rv = xfer_mgr.Make_file(wiki); if (rv) { meta_itm.Vrtl_repo_(repo_idx); // update repo_idx to whatever is found } return rv; } } /* NOTE_1:reset_main_exists this is primarily for Img_missing_wiki_1 and [[Image:Alcott-L.jpg|thumb|right|Louisa May Alcott]] first some details: . file pages exist in both en_wiki and in commons_wiki; w:File:Alcott-L.jpg; c:File:Alcott-L.jpg . images are slightly different (w: is darker than c:) . c was recently updated to redirect to File:Louisa May Alcott (1881 illustration).jpg the actual effect: . [[Image:Alcott-L.jpg|thumb|right|Louisa May Alcott]] in en.wikipedia should pull the w: one (not the c:) one . this behavior seems contrary to all other wiki behavior where c: is given primacy over w: .. EX: [[File:Tanks of WWI.ogg|thumb|thumbtime=12|alt=Primitive]] exists in both en_wiki and in commons, but the file only exists in commons . moreover this page has a special note about the image deliberately remainining in en_wiki the workaround/hack (described via intended sequence): 1: commons is defined as first repo_pair 2: image found in commons page (note that en_wiki is not checked for PERF reasons) 3: image is searched for in commons, but not found; note that both thumb and orig are missing 4: image will be searched for in en_wiki and found note that (4) however reuses the same meta which is marked as "not found" from the commons attempt . item will then have orig marked falsely as not-found one approach would be to create a new meta and send that into the chk_all function. this turned out to be problematic so, the workaround: if going into chk_all ...and orig was previous unknown ...but is now marked no then reset to unknown to give it a "clean" slate for the chk all in theory, the above statement seems fine, but it does seem hackish... */
1611_0
package domain; import java.util.*; public class Spel { SpelerGroep spelerGroep; Quiz quiz; int vraagIndex = 0; private List<Opdracht> opdrachten; /** * Maakt een nieuw spel aan met de gegeven spelergroep en quiz. * * @param spelers de groep van spelers * @param quiz de quiz */ public Spel(SpelerGroep spelers, Quiz quiz) { if(spelers == null || quiz == null) throw new IllegalArgumentException("Spelergroep of quiz is leeg"); this.spelerGroep = spelers; this.quiz = quiz; opdrachten = new LinkedList<>(quiz.getOpdrachten()); } /** * Geeft aan of er nog opdrachten zijn in de quiz. * * @return true als er geen opdrachten meer over zijn in de quiz, anders false */ public boolean isVoorbij() { if(vraagIndex == opdrachten.size()) return true; return false; } /** * Geeft de vraag van de volgende opdracht van de quiz. * * @return de vraag van de volgende opdracht van de quiz */ public String getVolgendeVraag() { return opdrachten.get(vraagIndex).getVraag(); } /** * Controleert of het antwoord juist is, kent punten toe en zet de volgende speler aan beurt. * Indien het antwoord juist is, krijgt de speler die aan beurt was 10 punten bij. Infien fout worden er geen punten toegekend. * * @param antwoord het antwoord van de speler op de vraag */ public boolean speel(String antwoord) { Opdracht opdracht = opdrachten.get(vraagIndex); volgendeVraag(); if(opdracht.getAntwoord().trim().equalsIgnoreCase(antwoord)){ spelerGroep.getSpelerAanBeurt().verhoogAantalPunten(10); return true; } spelerGroep.getEnVerplaatsSpelerAanBeurt(); return false; } /** * Geeft de speler terug met het meeste punten. * * @return de speler met het meeste punten */ public Speler getWinnaar() { Speler winnaar = new Speler("winnaar"); for(Speler s : spelerGroep.getSpelers()){ if(s.getAantalPunten() > winnaar.getAantalPunten()) winnaar = s; } return winnaar; } public Set<Speler> getWinnaars() { Set<Speler> winnaars = new HashSet<>(); int hoogstepunt = 0; for(Speler s : spelerGroep.getSpelers()){ if(s.getAantalPunten() == hoogstepunt){ winnaars.add(s); } if(s.getAantalPunten() > hoogstepunt){ winnaars.clear(); winnaars.add(s); } } return winnaars; } public int getHoogstePunt(){ return getWinnaar().getAantalPunten(); } /** * Geeft de naam van de speler terug die nu aan beurt is. * * @return de naam van de speler die nu aan beurt is */ public String getNaamSpelerAanBeurt() { return spelerGroep.getSpelerAanBeurt().getNaam(); } public int getVraagIndex() { return vraagIndex; } public void volgendeVraag(){ vraagIndex += 1; } }
martijnmeeldijk/TI-oplossingen
Semester_2/OOP/JCF1 legit/src/domain/Spel.java
918
/** * Maakt een nieuw spel aan met de gegeven spelergroep en quiz. * * @param spelers de groep van spelers * @param quiz de quiz */
block_comment
nl
package domain; import java.util.*; public class Spel { SpelerGroep spelerGroep; Quiz quiz; int vraagIndex = 0; private List<Opdracht> opdrachten; /** * Maakt een nieuw<SUF>*/ public Spel(SpelerGroep spelers, Quiz quiz) { if(spelers == null || quiz == null) throw new IllegalArgumentException("Spelergroep of quiz is leeg"); this.spelerGroep = spelers; this.quiz = quiz; opdrachten = new LinkedList<>(quiz.getOpdrachten()); } /** * Geeft aan of er nog opdrachten zijn in de quiz. * * @return true als er geen opdrachten meer over zijn in de quiz, anders false */ public boolean isVoorbij() { if(vraagIndex == opdrachten.size()) return true; return false; } /** * Geeft de vraag van de volgende opdracht van de quiz. * * @return de vraag van de volgende opdracht van de quiz */ public String getVolgendeVraag() { return opdrachten.get(vraagIndex).getVraag(); } /** * Controleert of het antwoord juist is, kent punten toe en zet de volgende speler aan beurt. * Indien het antwoord juist is, krijgt de speler die aan beurt was 10 punten bij. Infien fout worden er geen punten toegekend. * * @param antwoord het antwoord van de speler op de vraag */ public boolean speel(String antwoord) { Opdracht opdracht = opdrachten.get(vraagIndex); volgendeVraag(); if(opdracht.getAntwoord().trim().equalsIgnoreCase(antwoord)){ spelerGroep.getSpelerAanBeurt().verhoogAantalPunten(10); return true; } spelerGroep.getEnVerplaatsSpelerAanBeurt(); return false; } /** * Geeft de speler terug met het meeste punten. * * @return de speler met het meeste punten */ public Speler getWinnaar() { Speler winnaar = new Speler("winnaar"); for(Speler s : spelerGroep.getSpelers()){ if(s.getAantalPunten() > winnaar.getAantalPunten()) winnaar = s; } return winnaar; } public Set<Speler> getWinnaars() { Set<Speler> winnaars = new HashSet<>(); int hoogstepunt = 0; for(Speler s : spelerGroep.getSpelers()){ if(s.getAantalPunten() == hoogstepunt){ winnaars.add(s); } if(s.getAantalPunten() > hoogstepunt){ winnaars.clear(); winnaars.add(s); } } return winnaars; } public int getHoogstePunt(){ return getWinnaar().getAantalPunten(); } /** * Geeft de naam van de speler terug die nu aan beurt is. * * @return de naam van de speler die nu aan beurt is */ public String getNaamSpelerAanBeurt() { return spelerGroep.getSpelerAanBeurt().getNaam(); } public int getVraagIndex() { return vraagIndex; } public void volgendeVraag(){ vraagIndex += 1; } }