repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
cicavey/jzwave
src/main/java/net/rauros/jzwave/core/SensorType.java
2320
/** * Copyright 2012-2013 Chris Cavey <chris-jzwave@rauros.net> * * SOFTWARE NOTICE AND LICENSE * * This file is part of jzwave. * * jzwave is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jzwave is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with jzwave. If not, see <http://www.gnu.org/licenses/>. */ package net.rauros.jzwave.core; public enum SensorType { //@formatter:off TEMPERATURE("C", "F"), GENERAL("", "%"), LUMINANCE("%", "lux"), POWER("BTU/h", "W"), RELATIVE_HUMIDITY("%"), VELOCITY("mph", "m/s"), DIRECTION, ATOMSPHERIC_PRESSURE("inHg", "kPa"), BAROMETRIC_PRESSURE("inHg", "kPa"), SOLAR_RADITION("W/m^2"), DEW_POINT("F", "C"), RAIN_RATE("in/h", "mm/h"), TIDE_LEVEL("ft", "m"), WEIGHT("lb", "kg"), VOLTAGE("mV", "V"), CURRENT("mA", "A"), CO2("ppm"), AIR_FLOW("cfm", "m^3/h"), TANK_CAPACITY("l", "cbm", "gal"), DISTANCE("m", "cm", "ft"), ANGLE_POSITION("%", "deg N", "deg S"), ROTATION("rpm", "hz"), WATER_TEMPERATURE("C", "F"), SOIL_TEMPERATURE("C", "F"), SEISMIC_INTENSITY("mercalli", "EU macroseuismic", "liedu", "shindo"), SEISMIC_MAGNITUDE("local", "moment", "surface wave", "body wave"), ULTRAVIOLET, ELECTRICAL_RESISTIVITY("ohm"), ELECTRICAL_CONDUCTIVITY("siemens/m"), LOUDNESS("db", "dBA"), MOISTURE("%", "content", "k ohms", "water activity"); //@formatter:on private String[] units; private SensorType(String... units) { this.units = units; } public String units(int index) { if(units != null && units.length > 0) { if(index >= units.length) { return units[0]; } else { return units[index]; } } return ""; } public static SensorType byId(int id) { // sensor type is one based according to zwave return SensorType.values()[id - 1]; } }
lgpl-3.0
Shockah/Custom-Hearthstone
Engine/src/pl/shockah/hs/anim/GiveBuffAnim.java
702
package pl.shockah.hs.anim; import pl.shockah.hs.units.Buff; import pl.shockah.hs.units.Unit; public class GiveBuffAnim extends Anim { public final Unit unit; public final String name; public final Class<? extends Buff> cls; public final Object[] args; public GiveBuffAnim(Unit unit, String name, Object... args) { this.unit = unit; this.name = name; cls = null; this.args = args; } public GiveBuffAnim(Unit unit, Class<? extends Buff> cls, Object... args) { this.unit = unit; name = null; this.cls = cls; this.args = args; } public void finished(AnimQueue queue) { if (name != null) unit.addBuff(name, args); else if (cls != null) unit.addBuff(cls, args); } }
lgpl-3.0
Bang3DEngine/Bang
Compile/CompileDependencies/ThirdParty/libjpeg-turbo/java/TJExample.java
16929
/* * Copyright (C)2011-2012, 2014-2015, 2017 D. R. Commander. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the libjpeg-turbo Project 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 HOLDERS 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. */ /* * This program demonstrates how to compress, decompress, and transform JPEG * images using the TurboJPEG Java API */ import java.io.*; import java.awt.*; import java.awt.image.*; import java.nio.*; import javax.imageio.*; import javax.swing.*; import org.libjpegturbo.turbojpeg.*; public class TJExample implements TJCustomFilter { private static final String classname = new TJExample().getClass().getName(); private static final int DEFAULT_SUBSAMP = TJ.SAMP_444; private static final int DEFAULT_QUALITY = 95; private static final String[] subsampName = { "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1" }; private static final String[] colorspaceName = { "RGB", "YCbCr", "GRAY", "CMYK", "YCCK" }; /* DCT filter example. This produces a negative of the image. */ public void customFilter(ShortBuffer coeffBuffer, Rectangle bufferRegion, Rectangle planeRegion, int componentIndex, int transformIndex, TJTransform transform) throws TJException { for (int i = 0; i < bufferRegion.width * bufferRegion.height; i++) { coeffBuffer.put(i, (short)(-coeffBuffer.get(i))); } } private static void usage() throws Exception { System.out.println("\nUSAGE: java [Java options] " + classname + " <Input image> <Output image> [options]\n"); System.out.println("Input and output images can be in any image format that the Java Image I/O"); System.out.println("extensions understand. If either filename ends in a .jpg extension, then"); System.out.println("the TurboJPEG API will be used to compress or decompress the image.\n"); System.out.println("Compression Options (used if the output image is a JPEG image)"); System.out.println("--------------------------------------------------------------\n"); System.out.println("-subsamp <444|422|420|gray> = Apply this level of chrominance subsampling when"); System.out.println(" compressing the output image. The default is to use the same level of"); System.out.println(" subsampling as in the input image, if the input image is also a JPEG"); System.out.println(" image, or to use grayscale if the input image is a grayscale non-JPEG"); System.out.println(" image, or to use " + subsampName[DEFAULT_SUBSAMP] + " subsampling otherwise.\n"); System.out.println("-q <1-100> = Compress the output image with this JPEG quality level"); System.out.println(" (default = " + DEFAULT_QUALITY + ").\n"); System.out.println("Decompression Options (used if the input image is a JPEG image)"); System.out.println("---------------------------------------------------------------\n"); System.out.println("-scale M/N = Scale the input image by a factor of M/N when decompressing it."); System.out.print("(M/N = "); for (int i = 0; i < scalingFactors.length; i++) { System.out.print(scalingFactors[i].getNum() + "/" + scalingFactors[i].getDenom()); if (scalingFactors.length == 2 && i != scalingFactors.length - 1) System.out.print(" or "); else if (scalingFactors.length > 2) { if (i != scalingFactors.length - 1) System.out.print(", "); if (i == scalingFactors.length - 2) System.out.print("or "); } } System.out.println(")\n"); System.out.println("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 ="); System.out.println(" Perform one of these lossless transform operations on the input image"); System.out.println(" prior to decompressing it (these options are mutually exclusive.)\n"); System.out.println("-grayscale = Perform lossless grayscale conversion on the input image prior"); System.out.println(" to decompressing it (can be combined with the other transform operations"); System.out.println(" above.)\n"); System.out.println("-crop WxH+X+Y = Perform lossless cropping on the input image prior to"); System.out.println(" decompressing it. X and Y specify the upper left corner of the cropping"); System.out.println(" region, and W and H specify the width and height of the cropping region."); System.out.println(" X and Y must be evenly divible by the MCU block size (8x8 if the input"); System.out.println(" image was compressed using no subsampling or grayscale, 16x8 if it was"); System.out.println(" compressed using 4:2:2 subsampling, or 16x16 if it was compressed using"); System.out.println(" 4:2:0 subsampling.)\n"); System.out.println("General Options"); System.out.println("---------------\n"); System.out.println("-display = Display output image (Output filename need not be specified in this"); System.out.println(" case.)\n"); System.out.println("-fastupsample = Use the fastest chrominance upsampling algorithm available in"); System.out.println(" the underlying codec.\n"); System.out.println("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying"); System.out.println(" codec.\n"); System.out.println("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the"); System.out.println(" underlying codec.\n"); System.exit(1); } public static void main(String[] argv) { try { TJScalingFactor scalingFactor = new TJScalingFactor(1, 1); int outSubsamp = -1, outQual = -1; TJTransform xform = new TJTransform(); boolean display = false; int flags = 0; int width, height; String inFormat = "jpg", outFormat = "jpg"; BufferedImage img = null; byte[] imgBuf = null; if (argv.length < 2) usage(); if (argv[1].substring(0, 2).equalsIgnoreCase("-d")) display = true; /* Parse arguments. */ for (int i = 2; i < argv.length; i++) { if (argv[i].length() < 2) continue; else if (argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-sc") && i < argv.length - 1) { int match = 0; String[] scaleArg = argv[++i].split("/"); if (scaleArg.length == 2) { TJScalingFactor tempsf = new TJScalingFactor(Integer.parseInt(scaleArg[0]), Integer.parseInt(scaleArg[1])); for (int j = 0; j < scalingFactors.length; j++) { if (tempsf.equals(scalingFactors[j])) { scalingFactor = scalingFactors[j]; match = 1; break; } } } if (match != 1) usage(); } else if (argv[i].length() > 2 && argv[i].substring(0, 3).equalsIgnoreCase("-su") && i < argv.length - 1) { i++; if (argv[i].substring(0, 1).equalsIgnoreCase("g")) outSubsamp = TJ.SAMP_GRAY; else if (argv[i].equals("444")) outSubsamp = TJ.SAMP_444; else if (argv[i].equals("422")) outSubsamp = TJ.SAMP_422; else if (argv[i].equals("420")) outSubsamp = TJ.SAMP_420; else usage(); } else if (argv[i].substring(0, 2).equalsIgnoreCase("-q") && i < argv.length - 1) { outQual = Integer.parseInt(argv[++i]); if (outQual < 1 || outQual > 100) usage(); } else if (argv[i].substring(0, 2).equalsIgnoreCase("-g")) xform.options |= TJTransform.OPT_GRAY; else if (argv[i].equalsIgnoreCase("-hflip")) xform.op = TJTransform.OP_HFLIP; else if (argv[i].equalsIgnoreCase("-vflip")) xform.op = TJTransform.OP_VFLIP; else if (argv[i].equalsIgnoreCase("-transpose")) xform.op = TJTransform.OP_TRANSPOSE; else if (argv[i].equalsIgnoreCase("-transverse")) xform.op = TJTransform.OP_TRANSVERSE; else if (argv[i].equalsIgnoreCase("-rot90")) xform.op = TJTransform.OP_ROT90; else if (argv[i].equalsIgnoreCase("-rot180")) xform.op = TJTransform.OP_ROT180; else if (argv[i].equalsIgnoreCase("-rot270")) xform.op = TJTransform.OP_ROT270; else if (argv[i].equalsIgnoreCase("-custom")) xform.cf = new TJExample(); else if (argv[i].length() > 2 && argv[i].substring(0, 2).equalsIgnoreCase("-c") && i < argv.length - 1) { String[] cropArg = argv[++i].split("[x\\+]"); if (cropArg.length != 4) usage(); xform.width = Integer.parseInt(cropArg[0]); xform.height = Integer.parseInt(cropArg[1]); xform.x = Integer.parseInt(cropArg[2]); xform.y = Integer.parseInt(cropArg[3]); if (xform.x < 0 || xform.y < 0 || xform.width < 1 || xform.height < 1) usage(); xform.options |= TJTransform.OPT_CROP; } else if (argv[i].substring(0, 2).equalsIgnoreCase("-d")) display = true; else if (argv[i].equalsIgnoreCase("-fastupsample")) { System.out.println("Using fast upsampling code"); flags |= TJ.FLAG_FASTUPSAMPLE; } else if (argv[i].equalsIgnoreCase("-fastdct")) { System.out.println("Using fastest DCT/IDCT algorithm"); flags |= TJ.FLAG_FASTDCT; } else if (argv[i].equalsIgnoreCase("-accuratedct")) { System.out.println("Using most accurate DCT/IDCT algorithm"); flags |= TJ.FLAG_ACCURATEDCT; } else usage(); } /* Determine input and output image formats based on file extensions. */ String[] inFileTokens = argv[0].split("\\."); if (inFileTokens.length > 1) inFormat = inFileTokens[inFileTokens.length - 1]; String[] outFileTokens; if (display) outFormat = "bmp"; else { outFileTokens = argv[1].split("\\."); if (outFileTokens.length > 1) outFormat = outFileTokens[outFileTokens.length - 1]; } if (inFormat.equalsIgnoreCase("jpg")) { /* Input image is a JPEG image. Decompress and/or transform it. */ boolean doTransform = (xform.op != TJTransform.OP_NONE || xform.options != 0 || xform.cf != null); /* Read the JPEG file into memory. */ File jpegFile = new File(argv[0]); FileInputStream fis = new FileInputStream(jpegFile); int jpegSize = fis.available(); if (jpegSize < 1) { System.out.println("Input file contains no data"); System.exit(1); } byte[] jpegBuf = new byte[jpegSize]; fis.read(jpegBuf); fis.close(); TJDecompressor tjd; if (doTransform) { /* Transform it. */ TJTransformer tjt = new TJTransformer(jpegBuf); TJTransform[] xforms = new TJTransform[1]; xforms[0] = xform; xforms[0].options |= TJTransform.OPT_TRIM; TJDecompressor[] tjds = tjt.transform(xforms, 0); tjd = tjds[0]; tjt.close(); } else tjd = new TJDecompressor(jpegBuf); width = tjd.getWidth(); height = tjd.getHeight(); int inSubsamp = tjd.getSubsamp(); int inColorspace = tjd.getColorspace(); System.out.println((doTransform ? "Transformed" : "Input") + " Image (jpg): " + width + " x " + height + " pixels, " + subsampName[inSubsamp] + " subsampling, " + colorspaceName[inColorspace]); if (outFormat.equalsIgnoreCase("jpg") && doTransform && scalingFactor.isOne() && outSubsamp < 0 && outQual < 0) { /* Input image has been transformed, and no re-compression options have been selected. Write the transformed image to disk and exit. */ File outFile = new File(argv[1]); FileOutputStream fos = new FileOutputStream(outFile); fos.write(tjd.getJPEGBuf(), 0, tjd.getJPEGSize()); fos.close(); System.exit(0); } /* Scaling and/or a non-JPEG output image format and/or compression options have been selected, so we need to decompress the input/transformed image. */ width = scalingFactor.getScaled(width); height = scalingFactor.getScaled(height); if (outSubsamp < 0) outSubsamp = inSubsamp; if (!outFormat.equalsIgnoreCase("jpg")) img = tjd.decompress(width, height, BufferedImage.TYPE_INT_RGB, flags); else imgBuf = tjd.decompress(width, 0, height, TJ.PF_BGRX, flags); tjd.close(); } else { /* Input image is not a JPEG image. Load it into memory. */ img = ImageIO.read(new File(argv[0])); if (img == null) throw new Exception("Input image type not supported."); width = img.getWidth(); height = img.getHeight(); if (outSubsamp < 0) { if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) outSubsamp = TJ.SAMP_GRAY; else outSubsamp = DEFAULT_SUBSAMP; } System.out.println("Input Image: " + width + " x " + height + " pixels"); } System.gc(); if (!display) System.out.print("Output Image (" + outFormat + "): " + width + " x " + height + " pixels"); if (display) { /* Display the uncompressed image */ ImageIcon icon = new ImageIcon(img); JLabel label = new JLabel(icon, JLabel.CENTER); JOptionPane.showMessageDialog(null, label, "Output Image", JOptionPane.PLAIN_MESSAGE); } else if (outFormat.equalsIgnoreCase("jpg")) { /* Output image format is JPEG. Compress the uncompressed image. */ if (outQual < 0) outQual = DEFAULT_QUALITY; System.out.println(", " + subsampName[outSubsamp] + " subsampling, quality = " + outQual); TJCompressor tjc = new TJCompressor(); tjc.setSubsamp(outSubsamp); tjc.setJPEGQuality(outQual); if (img != null) tjc.setSourceImage(img, 0, 0, 0, 0); else tjc.setSourceImage(imgBuf, 0, 0, width, 0, height, TJ.PF_BGRX); byte[] jpegBuf = tjc.compress(flags); int jpegSize = tjc.getCompressedSize(); tjc.close(); /* Write the JPEG image to disk. */ File outFile = new File(argv[1]); FileOutputStream fos = new FileOutputStream(outFile); fos.write(jpegBuf, 0, jpegSize); fos.close(); } else { /* Output image format is not JPEG. Save the uncompressed image directly to disk. */ System.out.print("\n"); File outFile = new File(argv[1]); ImageIO.write(img, outFormat, outFile); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private static final TJScalingFactor[] scalingFactors = TJ.getScalingFactors(); };
lgpl-3.0
meteoinfo/meteoinfolib
src/org/meteoinfo/jts/geom/prep/PreparedGeometry.java
6474
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package org.meteoinfo.jts.geom.prep; import org.meteoinfo.jts.geom.*; /** * An interface for classes which prepare {@link Geometry}s * in order to optimize the performance * of repeated calls to specific geometric operations. * <p> * A given implementation may provide optimized implementations * for only some of the specified methods, * and delegate the remaining methods to the original {@link Geometry} operations. * An implementation may also only optimize certain situations, * and delegate others. * See the implementing classes for documentation about which methods and situations * they optimize. * <p> * Subclasses are intended to be thread-safe, to allow <code>PreparedGeometry</code> * to be used in a multi-threaded context * (which allows extracting maximum benefit from the prepared state). * * @author Martin Davis * */ public interface PreparedGeometry { /** * Gets the original {@link Geometry} which has been prepared. * * @return the base geometry */ Geometry getGeometry(); /** * Tests whether the base {@link Geometry} contains a given geometry. * * @param geom the Geometry to test * @return true if this Geometry contains the given Geometry * * @see Geometry#contains(Geometry) */ boolean contains(Geometry geom); /** * Tests whether the base {@link Geometry} properly contains a given geometry. * <p> * The <code>containsProperly</code> predicate has the following equivalent definitions: * <ul> * <li>Every point of the other geometry is a point of this geometry's interior. * <li>The DE-9IM Intersection Matrix for the two geometries matches * <code>[T**FF*FF*]</code> * </ul> * In other words, if the test geometry has any interaction with the boundary of the target * geometry the result of <tt>containsProperly</tt> is <tt>false</tt>. * This is different semantics to the {@link Geometry#contains} predicate, * in which test geometries can intersect the target's boundary and still be contained. * <p> * The advantage of using this predicate is that it can be computed * efficiently, since it avoids the need to compute the full topological relationship * of the input boundaries in cases where they intersect. * <p> * An example use case is computing the intersections * of a set of geometries with a large polygonal geometry. * Since <tt>intersection</tt> is a fairly slow operation, it can be more efficient * to use <tt>containsProperly</tt> to filter out test geometries which lie * wholly inside the area. In these cases the intersection is * known <i>a priori</i> to be exactly the original test geometry. * * @param geom the Geometry to test * @return true if this Geometry properly contains the given Geometry * * @see Geometry#contains * */ boolean containsProperly(Geometry geom); /** * Tests whether the base {@link Geometry} is covered by a given geometry. * * @param geom the Geometry to test * @return true if this Geometry is covered by the given Geometry * * @see Geometry#coveredBy(Geometry) */ boolean coveredBy(Geometry geom); /** * Tests whether the base {@link Geometry} covers a given geometry. * * @param geom the Geometry to test * @return true if this Geometry covers the given Geometry * * @see Geometry#covers(Geometry) */ boolean covers(Geometry geom); /** * Tests whether the base {@link Geometry} crosses a given geometry. * * @param geom the Geometry to test * @return true if this Geometry crosses the given Geometry * * @see Geometry#crosses(Geometry) */ boolean crosses(Geometry geom); /** * Tests whether the base {@link Geometry} is disjoint from a given geometry. * This method supports {@link GeometryCollection}s as input * * @param geom the Geometry to test * @return true if this Geometry is disjoint from the given Geometry * * @see Geometry#disjoint(Geometry) */ boolean disjoint(Geometry geom); /** * Tests whether the base {@link Geometry} intersects a given geometry. * This method supports {@link GeometryCollection}s as input * * @param geom the Geometry to test * @return true if this Geometry intersects the given Geometry * * @see Geometry#intersects(Geometry) */ boolean intersects(Geometry geom); /** * Tests whether the base {@link Geometry} overlaps a given geometry. * * @param geom the Geometry to test * @return true if this Geometry overlaps the given Geometry * * @see Geometry#overlaps(Geometry) */ boolean overlaps(Geometry geom); /** * Tests whether the base {@link Geometry} touches a given geometry. * * @param geom the Geometry to test * @return true if this Geometry touches the given Geometry * * @see Geometry#touches(Geometry) */ boolean touches(Geometry geom); /** * Tests whether the base {@link Geometry} is within a given geometry. * * @param geom the Geometry to test * @return true if this Geometry is within the given Geometry * * @see Geometry#within(Geometry) */ boolean within(Geometry geom); }
lgpl-3.0
ArticulatedSocialAgentsPlatform/HmiCore
HmiUtil/src/hmi/util/Ident.java
1300
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.util; /** * Ident is an interface for &quot;identifiable&quot; objcets, * that have a defined &quot;id&quot;. * @author Job Zwiers */ public interface Ident { /** * Returns an &quot;Id&quot; String that identifies the object */ String getId(); }
lgpl-3.0
mcapino/trajectorytools
src/main/java/tt/util/Counters.java
93
package tt.util; public class Counters { public static int expandedStatesCounter = 0; }
lgpl-3.0
CLovinr/WebPorter
maven/WebPorter/src/main/java/com/chenyg/wporter/ResponseDealtWithREST.java
5336
package com.chenyg.wporter; import java.io.IOException; import com.chenyg.wporter.base.*; import com.chenyg.wporter.log.WPLog; import com.chenyg.wporter.annotation.ThinkType; import com.chenyg.wporter.util.WPTool; /** * 带有rest处理的 */ class ResponseDealtWithREST extends ResponseDealt { /** * */ private static final long serialVersionUID = 1L; private ResponseDealt restDealt; private WPLog<?> wpLog; public ResponseDealtWithREST(WPLog<?> wpLog, boolean isDebug) { super(isDebug); this.wpLog = wpLog; this.restDealt = new SimpleRestResponseDealt(isDebug); } @Override public void writeResponse(WPRequest request, WPResponse response, WPObject wpObject, Object object, ResponseType responseType, WPorterType wPorterType, ThinkType thinkType) { WPPrinter wpPrinter = null; boolean needCloseCall = false, success = false; try { if (thinkType == ThinkType.REST) { restDealt.writeResponse(request, response, wpObject, object, responseType, wPorterType, thinkType); } else { setContentType(request, response, object, responseType, wPorterType); wpPrinter = response.getPrinter(); wpPrinter.print(object); wpPrinter.flush(); success = true; needCloseCall = true; } } catch (IOException e) { wpLog.error(e.getMessage(), e); } catch (Exception e) { wpLog.error(e.getMessage(), e); try { response.sendError(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (IOException e1) { wpLog.error(e1.getMessage(), e1); } } finally { if (wpPrinter != null) { try { wpPrinter.close(); } catch (IOException e) { success = false; } } if (needCloseCall && wpObject != null) { wpObject.closeListenerCall(success); } } } private static class SimpleRestResponseDealt extends ResponseDealt { /** * */ private static final long serialVersionUID = 1L; public SimpleRestResponseDealt(boolean isDebug) { super(isDebug); } @Override public void writeResponse(WPRequest request, WPResponse response, WPObject wpObject, Object object, ResponseType responseType, WPorterType wPorterType, ThinkType thinkType) { WPPrinter wpPrinter = null; boolean needCloseCall = false, success = false; try { if (willResponse(request, response, object, responseType)) { setContentType(request, response, object, responseType, wPorterType); wpPrinter = response.getPrinter(); wpPrinter.print(object); wpPrinter.flush(); needCloseCall = true; success = true; } } catch (IOException e) { } catch (Exception e) { try { response.sendError(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (IOException e1) { e1.printStackTrace(); } } finally { if (wpPrinter != null) { try { wpPrinter.close(); } catch (IOException e) { success = false; } } if (needCloseCall && wpObject != null) { wpObject.closeListenerCall(success); } } } private boolean willResponse(WPRequest request, WPResponse response, Object object, ResponseType responseType) { boolean willR = true; if (object != null && (object instanceof JResponse)) { willR = false; JResponse jResponse = (JResponse) object; int code = jResponse.getCode().toCode(); switch (code) { case HttpStatusCode.NO_CONTENT: case HttpStatusCode.NOT_FOUND: response.setStatus(code); break; default: if (HttpStatusCode.isHttpStatusCode(code)) { response.setStatus(code); } else { response.setStatus(HttpStatusCode.OK); } willR = true; break; } } return willR; } } }
lgpl-3.0
Ortolang/diffusion
comp/src/main/java/fr/ortolang/diffusion/runtime/RuntimeServiceBean.java
40554
package fr.ortolang.diffusion.runtime; /* * #%L * ORTOLANG * A online network structure for hosting language resources and tools. * * Jean-Marie Pierrel / ATILF UMR 7118 - CNRS / Université de Lorraine * Etienne Petitjean / ATILF UMR 7118 - CNRS * Jérôme Blanchard / ATILF UMR 7118 - CNRS * Bertrand Gaiffe / ATILF UMR 7118 - CNRS * Cyril Pestel / ATILF UMR 7118 - CNRS * Marie Tonnelier / ATILF UMR 7118 - CNRS * Ulrike Fleury / ATILF UMR 7118 - CNRS * Frédéric Pierre / ATILF UMR 7118 - CNRS * Céline Moro / ATILF UMR 7118 - CNRS * * This work is based on work done in the equipex ORTOLANG (http://www.ortolang.fr/), by several Ortolang contributors (mainly CNRTL and SLDR) * ORTOLANG is funded by the French State program "Investissements d'Avenir" ANR-11-EQPX-0032 * %% * Copyright (C) 2013 - 2015 Ortolang Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ejb.EJB; import javax.ejb.Local; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.activiti.engine.task.IdentityLink; import org.jboss.ejb3.annotation.SecurityDomain; import fr.ortolang.diffusion.OrtolangConfig; import fr.ortolang.diffusion.OrtolangEvent; import fr.ortolang.diffusion.OrtolangEvent.ArgumentsBuilder; import fr.ortolang.diffusion.OrtolangException; import fr.ortolang.diffusion.OrtolangObject; import fr.ortolang.diffusion.OrtolangObjectIdentifier; import fr.ortolang.diffusion.OrtolangObjectSize; import fr.ortolang.diffusion.OrtolangObjectXmlExportHandler; import fr.ortolang.diffusion.OrtolangObjectXmlImportHandler; import fr.ortolang.diffusion.membership.MembershipService; import fr.ortolang.diffusion.membership.MembershipServiceException; import fr.ortolang.diffusion.membership.entity.Profile; import fr.ortolang.diffusion.notification.NotificationService; import fr.ortolang.diffusion.notification.NotificationServiceException; import fr.ortolang.diffusion.referential.ReferentialService; import fr.ortolang.diffusion.registry.IdentifierAlreadyRegisteredException; import fr.ortolang.diffusion.registry.IdentifierNotRegisteredException; import fr.ortolang.diffusion.registry.KeyAlreadyExistsException; import fr.ortolang.diffusion.registry.KeyLockedException; import fr.ortolang.diffusion.registry.KeyNotFoundException; import fr.ortolang.diffusion.registry.RegistryService; import fr.ortolang.diffusion.registry.RegistryServiceException; import fr.ortolang.diffusion.runtime.engine.RuntimeEngine; import fr.ortolang.diffusion.runtime.engine.RuntimeEngineEvent; import fr.ortolang.diffusion.runtime.engine.RuntimeEngineException; import fr.ortolang.diffusion.runtime.entity.HumanTask; import fr.ortolang.diffusion.runtime.entity.Process; import fr.ortolang.diffusion.runtime.entity.Process.State; import fr.ortolang.diffusion.runtime.entity.ProcessType; import fr.ortolang.diffusion.runtime.xml.ProcessExportHandler; import fr.ortolang.diffusion.security.authorisation.AccessDeniedException; import fr.ortolang.diffusion.security.authorisation.AuthorisationService; import fr.ortolang.diffusion.security.authorisation.AuthorisationServiceException; @Local(RuntimeService.class) @Stateless(name = RuntimeService.SERVICE_NAME) @SecurityDomain("ortolang") @PermitAll public class RuntimeServiceBean implements RuntimeService { private static final Logger LOGGER = Logger.getLogger(RuntimeServiceBean.class.getName()); private static final String DEFAULT_RUNTIME_HOME = "/runtime"; private static final String TRACE_FILE_EXTENSION = ".log"; private static final String[] OBJECT_TYPE_LIST = new String[] { Process.OBJECT_TYPE }; private static final String[][] OBJECT_PERMISSIONS_LIST = new String[][] { { Process.OBJECT_TYPE, "read,update,delete,start,abort" } }; private static Path base; @EJB private RegistryService registry; @EJB private MembershipService membership; @EJB private AuthorisationService authorisation; @EJB private NotificationService notification; @EJB private RuntimeEngine engine; @PersistenceContext(unitName = "ortolangPU") private EntityManager em; @Resource private SessionContext ctx; public RuntimeServiceBean() { } public Path getBase() throws RuntimeServiceException { if (base == null) { try { base = Paths.get(OrtolangConfig.getInstance().getHomePath().toString(), DEFAULT_RUNTIME_HOME); Files.createDirectories(base); } catch (Exception e) { LOGGER.log(Level.SEVERE, "unable to build base working directory for runtime service", e); throw new RuntimeServiceException("unable to build base working directory for runtime service", e); } } return base; } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void importProcessTypes() throws RuntimeServiceException { LOGGER.log(Level.INFO, "Importing configured process types"); try { String[] types = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.RUNTIME_DEFINITIONS).split(","); engine.deployDefinitions(types); } catch (RuntimeEngineException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while importing process types", e); throw new RuntimeServiceException("unable to import configured process types", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<ProcessType> listProcessTypes(boolean onlyLatestVersions) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Listing process types of " + (onlyLatestVersions ? "latest" : "all" + " versions")); try { return engine.listProcessTypes(onlyLatestVersions); } catch (RuntimeEngineException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing process types", e); throw new RuntimeServiceException("unable to list process types", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public Process createProcess(String key, String type, String name, String workspace) throws RuntimeServiceException, AccessDeniedException { LOGGER.log(Level.INFO, "Creating new process of type: " + type); try { String caller = membership.getProfileKeyForConnectedIdentifier(); ProcessType ptype = engine.getProcessTypeByKey(type); if (ptype == null) { throw new RuntimeServiceException("unable to find a process type named: " + type); } String id = UUID.randomUUID().toString(); Process process = new Process(); process.setId(id); process.setInitier(caller); process.setKey(key); process.setName(name); process.setWorkspace(workspace); process.setType(type); process.setState(State.PENDING); process.appendLog(new Date() + " PROCESS CREATED BY " + caller); em.persist(process); registry.register(key, new OrtolangObjectIdentifier(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, id), caller); authorisation.createPolicy(key, caller); ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder(2).addArgument("type", type).addArgument("workspace", workspace); notification.throwEvent(key, caller, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "create"), argumentsBuilder.build()); return process; } catch (RuntimeEngineException | RegistryServiceException | KeyAlreadyExistsException | IdentifierAlreadyRegisteredException | AuthorisationServiceException | NotificationServiceException e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while creating process", e); throw new RuntimeServiceException("unable to create process ", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void startProcess(String key, Map<String, Object> variables) throws RuntimeServiceException, AccessDeniedException { LOGGER.log(Level.INFO, "Starting process with key: " + key); try { String caller = membership.getProfileKeyForConnectedIdentifier(); List<String> subjects = membership.getConnectedIdentifierSubjects(); authorisation.checkPermission(key, subjects, "start"); OrtolangObjectIdentifier identifier = registry.lookup(key); checkObjectType(identifier, Process.OBJECT_TYPE); Process process = em.find(Process.class, identifier.getId()); if (process == null) { throw new RuntimeServiceException("unable to find a process for id " + identifier.getId()); } if (!process.getState().equals(State.PENDING)) { throw new RuntimeServiceException("unable to start process, state is not " + State.PENDING); } process.setKey(key); process.appendLog(new Date() + " PROCESS STATE CHANGED TO " + State.SUBMITTED + " BY " + caller); process.setState(State.SUBMITTED); process.setStart(System.currentTimeMillis()); em.persist(process); variables.put(Process.INITIER_VAR_NAME, process.getInitier()); if (process.getWorkspace() != null && process.getWorkspace().length() > 0) { variables.put(Process.WSKEY_VAR_NAME, process.getWorkspace()); } engine.startProcess(process.getType(), process.getId(), variables); registry.update(key); notification.throwEvent(key, caller, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "start")); } catch (KeyLockedException | MembershipServiceException | KeyNotFoundException | AuthorisationServiceException | RegistryServiceException | RuntimeEngineException | NotificationServiceException e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while submitting process for start", e); throw new RuntimeServiceException("unable to submit process for start", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void abortProcess(String key) throws RuntimeServiceException, AccessDeniedException, KeyNotFoundException { LOGGER.log(Level.INFO, "Killing process with key: " + key); try { String caller = membership.getProfileKeyForConnectedIdentifier(); List<String> subjects = membership.getConnectedIdentifierSubjects(); authorisation.checkPermission(key, subjects, "abort"); OrtolangObjectIdentifier identifier = registry.lookup(key); checkObjectType(identifier, Process.OBJECT_TYPE); Process process = em.find(Process.class, identifier.getId()); if (process == null) { throw new RuntimeServiceException("unable to find a process for id " + identifier.getId()); } if (!process.getState().equals(State.RUNNING)) { throw new RuntimeServiceException("unable to kill process, state is not " + State.RUNNING); } process.setKey(key); process.appendLog(new Date() + " PROCESS STATE CHANGED TO " + State.ABORTED + " BY " + caller); process.setState(State.ABORTED); process.setStop(System.currentTimeMillis()); em.persist(process); engine.deleteProcess(process.getId()); registry.update(key); notification.throwEvent(key, caller, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "abort")); } catch (KeyLockedException | MembershipServiceException | AuthorisationServiceException | RegistryServiceException | RuntimeEngineException | NotificationServiceException e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while killing process", e); throw new RuntimeServiceException("unable to kill process", e); } } @Override @RolesAllowed("admin") @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Process> systemListProcesses(State state) throws RuntimeServiceException, AccessDeniedException { LOGGER.log(Level.INFO, "#SYSTEM# Listing all processes in " + ((state != null) ? "state=" + state : "all states")); try { String caller = membership.getProfileKeyForConnectedIdentifier(); if (!caller.equals(MembershipService.SUPERUSER_IDENTIFIER)) { throw new AccessDeniedException("only super user can list all processes"); } TypedQuery<Process> query; if (state != null) { query = em.createNamedQuery("findProcessByState", Process.class).setParameter("state", state); } else { query = em.createNamedQuery("findAllProcess", Process.class); } List<Process> rprocesses = new ArrayList<Process>(); for (Process process : query.getResultList()) { try { String ikey = registry.lookup(process.getObjectIdentifier()); process.setKey(ikey); rprocesses.add(process); } catch (IdentifierNotRegisteredException e) { LOGGER.log(Level.WARNING, "unregistered process found in storage for id: " + process.getId()); } } return rprocesses; } catch (RegistryServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing processes", e); throw new RuntimeServiceException("unable to list processes", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Process> systemListUserProcesses(String username, State state) throws RuntimeServiceException { LOGGER.log(Level.INFO, "#SYSTEM# Listing processes for user [" + username + "] in " + ((state != null) ? "state=" + state : "all states")); return listUserProcesses(username, state); } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Process> listCallerProcesses(State state) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Listing caller processes in " + ((state != null) ? "state=" + state : "all states")); String caller = membership.getProfileKeyForConnectedIdentifier(); return listUserProcesses(caller, state); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) private List<Process> listUserProcesses(String username, State state) throws RuntimeServiceException { try { TypedQuery<Process> query; if (state != null) { query = em.createNamedQuery("findProcessByIniterAndState", Process.class).setParameter("state", state).setParameter("initier", username); } else { query = em.createNamedQuery("findProcessByInitier", Process.class).setParameter("initier", username); } List<Process> rprocesses = new ArrayList<>(); for (Process process : query.getResultList()) { try { String ikey = registry.lookup(process.getObjectIdentifier()); process.setKey(ikey); rprocesses.add(process); } catch (IdentifierNotRegisteredException e) { LOGGER.log(Level.WARNING, "unregistered process found in storage for id: " + process.getId()); } } return rprocesses; } catch (RegistryServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing processes", e); throw new RuntimeServiceException("unable to list processes", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Process> listWorkspaceProcesses(String wskey, State state) throws RuntimeServiceException, AccessDeniedException { LOGGER.log(Level.INFO, "Listing workspace processes in " + ((state != null) ? "state=" + state : "all states")); try { TypedQuery<Process> query; if (state != null) { query = em.createNamedQuery("findProcessByWorkspaceAndState", Process.class).setParameter("state", state).setParameter("workspace", wskey); } else { query = em.createNamedQuery("findProcessByWorkspace", Process.class).setParameter("workspace", wskey); } List<Process> rprocesses = new ArrayList<Process>(); for (Process process : query.getResultList()) { try { String ikey = registry.lookup(process.getObjectIdentifier()); process.setKey(ikey); rprocesses.add(process); } catch (IdentifierNotRegisteredException e) { LOGGER.log(Level.WARNING, "unregistered process found in storage for id: " + process.getId()); } } return rprocesses; } catch (RegistryServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing processes", e); throw new RuntimeServiceException("unable to list processes", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public Process readProcess(String key) throws RuntimeServiceException, KeyNotFoundException, AccessDeniedException { LOGGER.log(Level.INFO, "Reading process with key: " + key); try { List<String> subjects = membership.getConnectedIdentifierSubjects(); authorisation.checkPermission(key, subjects, "read"); OrtolangObjectIdentifier identifier = registry.lookup(key); checkObjectType(identifier, Process.OBJECT_TYPE); Process instance = em.find(Process.class, identifier.getId()); if (instance == null) { throw new RuntimeServiceException("unable to find a process with id: " + identifier.getId()); } instance.setKey(key); return instance; } catch (MembershipServiceException | AuthorisationServiceException | RegistryServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while reading process", e); throw new RuntimeServiceException("unable to read process", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public Map<String, Object> listProcessVariables(String key) throws RuntimeServiceException, KeyNotFoundException, AccessDeniedException { LOGGER.log(Level.INFO, "Listing process variables for process with key: " + key); try { List<String> subjects = membership.getConnectedIdentifierSubjects(); authorisation.checkPermission(key, subjects, "read"); OrtolangObjectIdentifier identifier = registry.lookup(key); checkObjectType(identifier, Process.OBJECT_TYPE); Process instance = em.find(Process.class, identifier.getId()); if (instance == null) { throw new RuntimeServiceException("unable to find a process with id: " + identifier.getId()); } if ( !instance.getState().equals(State.RUNNING) ) { throw new RuntimeServiceException("listing process variables is only for process in state: " + State.RUNNING); } return engine.listProcessVariables(instance.getId()); } catch (MembershipServiceException | AuthorisationServiceException | RegistryServiceException | RuntimeEngineException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing process variables", e); throw new RuntimeServiceException("unable to list process variables", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public File readProcessTrace(String key) throws RuntimeServiceException, KeyNotFoundException, AccessDeniedException { LOGGER.log(Level.INFO, "Reading trace of process with key: " + key); try { List<String> subjects = membership.getConnectedIdentifierSubjects(); authorisation.checkPermission(key, subjects, "read"); OrtolangObjectIdentifier identifier = registry.lookup(key); checkObjectType(identifier, Process.OBJECT_TYPE); Process instance = em.find(Process.class, identifier.getId()); if (instance == null) { throw new RuntimeServiceException("unable to find a process with id: " + identifier.getId()); } Path trace = Paths.get(getBase().toString(), instance.getId() + TRACE_FILE_EXTENSION); if (Files.exists(trace)) { return trace.toFile(); } else { throw new RuntimeServiceException("unable to find trace file for process with key: " + key); } } catch (MembershipServiceException | AuthorisationServiceException | RegistryServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while reading process", e); throw new RuntimeServiceException("unable to read process", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void updateProcessState(String pid, State state) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Updating state of process with pid: " + pid); try { Process process = em.find(Process.class, pid); if (process == null) { throw new RuntimeServiceException("unable to find a process with id: " + pid); } process.setState(state); if (state.equals(State.ABORTED) || state.equals(State.COMPLETED) || state.equals(State.SUSPENDED)) { process.setStop(System.currentTimeMillis()); } process.appendLog(new Date() + " PROCESS STATE CHANGED TO " + state); em.merge(process); String key = registry.lookup(process.getObjectIdentifier()); registry.update(key); ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder("state", state.name()); notification.throwEvent(key, RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "change-state"), argumentsBuilder.build()); } catch (Exception e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while updating process state", e); throw new RuntimeServiceException("unable to update process state", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void updateProcessStatus(String pid, String status, String explanation) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Updating status of process with pid: " + pid); try { Process process = em.find(Process.class, pid); if (process == null) { throw new RuntimeServiceException("unable to find a process with id: " + pid); } process.setStatus(status); process.setExplanation(explanation); process.appendLog(new Date() + " PROCESS STATUS CHANGED TO " + status); em.merge(process); String key = registry.lookup(process.getObjectIdentifier()); registry.update(key); ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder("status", status).addArgument("explanation", explanation); notification.throwEvent(key, RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "change-status"), argumentsBuilder.build()); } catch (Exception e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while updating process status", e); throw new RuntimeServiceException("unable to update process status", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void appendProcessLog(String pid, String log) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Appending log to process with pid: " + pid); try { Process process = em.find(Process.class, pid); if (process == null) { throw new RuntimeServiceException("unable to find a process with id: " + pid); } process.appendLog(log); em.merge(process); String key = registry.lookup(process.getObjectIdentifier()); registry.update(key); appendProcessTrace(pid, log + "\r\n"); ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder("message", log); notification.throwEvent(key, RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "log-info"), argumentsBuilder.build()); } catch (Exception e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while appending log to process", e); throw new RuntimeServiceException("unable to append process log", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public void appendProcessTrace(String pid, String trace) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Appending trace to process with pid: " + pid); try { Path logfile = Paths.get(getBase().toString(), pid + TRACE_FILE_EXTENSION); if (!Files.exists(logfile)) { String head = "## TRACE FILE FOR PROCESS WITH PID: " + pid + "\r\n##\r\n\r\n"; Files.write(logfile, head.getBytes(), StandardOpenOption.CREATE); } Files.write(logfile, trace.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while appending trace to process", e); throw new RuntimeServiceException("unable to append process trace", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void updateProcessActivity(String pid, String name, int progress) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Updating activity of process with pid: " + pid); try { Process process = em.find(Process.class, pid); if (process == null) { throw new RuntimeServiceException("unable to find a process with id: " + pid); } process.setActivity(name); em.merge(process); String key = registry.lookup(process.getObjectIdentifier()); registry.update(key); ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder("activity", name); argumentsBuilder.addArgument("progress", Integer.toString(progress)); notification.throwEvent(key, RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, Process.OBJECT_TYPE, "update-activity"), argumentsBuilder.build()); } catch (Exception e) { ctx.setRollbackOnly(); LOGGER.log(Level.SEVERE, "unexpected error occurred while updating process activity", e); throw new RuntimeServiceException("unable to update process activity", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void pushTaskEvent(String pid, String tid, Set<IdentityLink> candidates, String assignee, RuntimeEngineEvent.Type type) { LOGGER.log(Level.INFO, "Pushing task event to notification service, pid:" + pid + ", tid: " + tid); try { ArgumentsBuilder argumentsBuilder = new ArgumentsBuilder("tid", tid); String eventName = type.name().substring(type.name().lastIndexOf("_") + 1).toLowerCase(); if (candidates != null) { for (IdentityLink candidate : candidates) { if (candidate.getUserId() != null) { argumentsBuilder.addArgument("user", candidate.getUserId()); } if (candidate.getGroupId() != null) { argumentsBuilder.addArgument("group", candidate.getGroupId()); } } } if (assignee != null) { argumentsBuilder.addArgument("assignee", assignee); } notification.throwEvent(tid, RuntimeService.SERVICE_NAME, HumanTask.OBJECT_TYPE, OrtolangEvent.buildEventType(RuntimeService.SERVICE_NAME, HumanTask.OBJECT_TYPE, eventName),argumentsBuilder.build()); } catch (NotificationServiceException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while pushing task event", e); } } @Override @RolesAllowed("admin") @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<HumanTask> systemListTasks() throws RuntimeServiceException { LOGGER.log(Level.INFO, "#SYSTEM# Listing all tasks"); try { return engine.listAllTasks(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing all tasks", e); throw new RuntimeServiceException("unable to list all tasks", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<HumanTask> listCandidateTasks() throws RuntimeServiceException, AccessDeniedException, KeyNotFoundException { LOGGER.log(Level.INFO, "Listing candidate tasks"); String caller = membership.getProfileKeyForConnectedIdentifier(); try { List<String> groups = membership.getProfileGroups(caller); return listUserCandidateTasks(caller, groups); } catch (MembershipServiceException e) { throw new RuntimeServiceException("unable to list user's groups", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<HumanTask> systemListUserCandidateTasks(String username) throws RuntimeServiceException, KeyNotFoundException { LOGGER.log(Level.INFO, "#SYSTEM# Listing candidate tasks"); try { Profile profile = membership.systemReadProfile(username); return listUserCandidateTasks(username, Arrays.asList(profile.getGroups())); } catch (MembershipServiceException e) { throw new RuntimeServiceException("unable to list user's groups", e); } } @TransactionAttribute(TransactionAttributeType.SUPPORTS) private List<HumanTask> listUserCandidateTasks(String username, List<String> groups) throws RuntimeServiceException { try { if (username.equals(MembershipService.SUPERUSER_IDENTIFIER) ) { return engine.listAllUnassignedTasks(); } else { return engine.listCandidateTasks(username, groups); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing candidate tasks", e); throw new RuntimeServiceException("unable to list candidate tasks", e); } } @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<HumanTask> listAssignedTasks() throws RuntimeServiceException { LOGGER.log(Level.INFO, "Listing assigned tasks"); try { String caller = membership.getProfileKeyForConnectedIdentifier(); return engine.listAssignedTasks(caller); } catch (Exception e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while listing assigned tasks", e); throw new RuntimeServiceException("unable to list assigned tasks", e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void claimTask(String id) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Claiming task with tid: " + id); try { String caller = membership.getProfileKeyForConnectedIdentifier(); List<String> groups = membership.getProfileGroups(caller); if (caller.equals(MembershipService.SUPERUSER_IDENTIFIER) || engine.isCandidate(id, caller, groups)) { engine.claimTask(id, caller); } else { throw new RuntimeServiceException("connected identifier is not allowed to claim this task because not in candidates users"); } } catch (RuntimeEngineException | MembershipServiceException | KeyNotFoundException | AccessDeniedException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while claiming task", e); throw new RuntimeServiceException("unable to claim task with id: " + id, e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void unclaimTask(String id) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Unclaiming task with tid: " + id); try { String caller = membership.getProfileKeyForConnectedIdentifier(); if (caller.equals(MembershipService.SUPERUSER_IDENTIFIER) || engine.isAssigned(id, caller)) { engine.unclaimTask(id); } else { throw new RuntimeServiceException("connected identifier is not allowed to unclaim this task because not assigned user"); } } catch (RuntimeEngineException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while unclaiming task", e); throw new RuntimeServiceException("unable to unclaim task with id: " + id, e); } } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void completeTask(String id, Map<String, Object> variables) throws RuntimeServiceException { LOGGER.log(Level.INFO, "Complete task with tid: " + id); try { String caller = membership.getProfileKeyForConnectedIdentifier(); if (caller.equals(MembershipService.SUPERUSER_IDENTIFIER) || engine.isAssigned(id, caller)) { engine.completeTask(id, variables); } else { throw new RuntimeServiceException("connected identifier is not allowed to complete this task because not assigned user"); } } catch (RuntimeEngineException e) { LOGGER.log(Level.SEVERE, "unexpected error occurred while completing task", e); throw new RuntimeServiceException("unable to complete task with id: " + id, e); } } @Override public String getServiceName() { return RuntimeService.SERVICE_NAME; } @Override public Map<String, String> getServiceInfos() { return Collections.emptyMap(); } @Override public String[] getObjectTypeList() { return OBJECT_TYPE_LIST; } @Override public String[] getObjectPermissionsList(String type) throws OrtolangException { for (int i = 0; i < OBJECT_PERMISSIONS_LIST.length; i++) { if (OBJECT_PERMISSIONS_LIST[i][0].equals(type)) { return OBJECT_PERMISSIONS_LIST[i][1].split(","); } } throw new OrtolangException("Unable to find object permissions list for object type : " + type); } @Override public OrtolangObject findObject(String key) throws OrtolangException { try { OrtolangObjectIdentifier identifier = registry.lookup(key); if (!identifier.getService().equals(RuntimeService.SERVICE_NAME)) { throw new OrtolangException("object identifier " + identifier + " does not refer to service " + getServiceName()); } if (identifier.getType().equals(Process.OBJECT_TYPE)) { return readProcess(key); } throw new OrtolangException("object identifier " + identifier + " does not refer to service " + getServiceName()); } catch (RuntimeServiceException | RegistryServiceException | KeyNotFoundException e) { throw new OrtolangException("unable to find an object for key " + key); } } // @TODO implement getSize @Override public OrtolangObjectSize getSize(String key) throws OrtolangException { return null; } @Override public OrtolangObjectXmlExportHandler getObjectXmlExportHandler(String key) throws OrtolangException { try { OrtolangObjectIdentifier identifier = registry.lookup(key); if (!identifier.getService().equals(ReferentialService.SERVICE_NAME)) { throw new OrtolangException("object identifier " + identifier + " does not refer to service " + getServiceName()); } switch (identifier.getType()) { case Process.OBJECT_TYPE: Process process = em.find(Process.class, identifier.getId()); if (process == null) { throw new OrtolangException("unable to load process with id [" + identifier.getId() + "] from storage"); } return new ProcessExportHandler(process); } } catch (RegistryServiceException | KeyNotFoundException e) { throw new OrtolangException("unable to build object export handler " + key, e); } throw new OrtolangException("unable to build object export handler for key " + key); } @Override public OrtolangObjectXmlImportHandler getObjectXmlImportHandler(String type) throws OrtolangException { // TODO throw new OrtolangException("NOT IMPLEMENTED"); } private void checkObjectType(OrtolangObjectIdentifier identifier, String objectType) throws RuntimeServiceException { if (!identifier.getService().equals(getServiceName())) { throw new RuntimeServiceException("object identifier " + identifier + " does not refer to service " + getServiceName()); } if (!identifier.getType().equals(objectType)) { throw new RuntimeServiceException("object identifier " + identifier + " does not refer to an object of type " + objectType); } } }
lgpl-3.0
ahoereth/RobotTrajectoryAnalyzer
src/robotTA/types/Movement.java
2836
/* First created by JCasGen Tue Jun 09 13:22:47 CEST 2015 */ package robotTA.types; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.TOP_Type; import org.apache.uima.jcas.tcas.Annotation; /** * Updated by JCasGen Tue Jun 09 13:22:47 CEST 2015 * XML source: /home/ahoereth/Devel/RobotTrajectoryAnalyzer/src/robotTA/types/TypeSystem.xml * @generated */ public class Movement extends Annotation { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(Movement.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated * @return index of the type */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected Movement() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated * @param addr low level Feature Structure reference * @param type the type of this Feature Structure */ public Movement(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs */ public Movement(JCas jcas) { super(jcas); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs * @param begin offset to the begin spot in the SofA * @param end offset to the end spot in the SofA */ public Movement(JCas jcas, int begin, int end) { super(jcas); setBegin(begin); setEnd(end); readObject(); } /** * <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> * * @generated modifiable */ private void readObject() {/*default - does nothing empty block */} //*--------------* //* Feature: jointName /** getter for jointName - gets * @generated * @return value of the feature */ public String getJointName() { if (Movement_Type.featOkTst && ((Movement_Type)jcasType).casFeat_jointName == null) jcasType.jcas.throwFeatMissing("jointName", "robotTA.types.Movement"); return jcasType.ll_cas.ll_getStringValue(addr, ((Movement_Type)jcasType).casFeatCode_jointName);} /** setter for jointName - sets * @generated * @param v value to set into the feature */ public void setJointName(String v) { if (Movement_Type.featOkTst && ((Movement_Type)jcasType).casFeat_jointName == null) jcasType.jcas.throwFeatMissing("jointName", "robotTA.types.Movement"); jcasType.ll_cas.ll_setStringValue(addr, ((Movement_Type)jcasType).casFeatCode_jointName, v);} }
lgpl-3.0
StephaneSeyvoz/mindEd
org.ow2.mindEd.adl.editor.graphic.ui/customsrc/org/ow2/mindEd/adl/editor/graphic/ui/custom/tools/InterfaceCreationTool.java
4174
package org.ow2.mindEd.adl.editor.graphic.ui.custom.tools; import java.util.Collection; import java.util.List; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.transaction.RollbackException; import org.eclipse.emf.transaction.impl.TransactionImpl; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter; import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramCommandStack; import org.eclipse.gmf.runtime.diagram.ui.tools.UnspecifiedTypeCreationTool; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.PlatformUI; import org.ow2.mindEd.adl.InterfaceDefinition; import org.ow2.mindEd.adl.custom.impl.InterfaceDefinitionCustomImpl; import org.ow2.mindEd.adl.editor.graphic.ui.custom.edit.commands.MindDiagramUpdateAllCommand; import org.ow2.mindEd.adl.editor.graphic.ui.custom.wizards.InterfaceInformation; import org.ow2.mindEd.adl.editor.graphic.ui.custom.wizards.InterfaceCreationWizard; import org.ow2.mindEd.ide.core.ModelToProjectUtil; import org.ow2.mindEd.ide.model.MindFile; public class InterfaceCreationTool extends UnspecifiedTypeCreationTool{ @Override protected void performCreation(int button) { antiScroll = true; EditPartViewer viewer = getCurrentViewer(); Command c = getCurrentCommand(); selectAddedObject(viewer, DiagramCommandStack.getReturnValues(c)); if(c != null) { InterfaceCreationWizard wizWizard = new InterfaceCreationWizard(null); WizardDialog wizDialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), wizWizard); wizDialog.setBlockOnOpen(true); if(wizDialog.open() == WizardDialog.OK) { executeCurrentCommand(); InterfaceInformation interfaceInformation = wizWizard.getNewInterfaceInformation(); Collection<?> commandReturnValue = DiagramCommandStack.getReturnValues(c); for(Object elementRequest : commandReturnValue) { if(elementRequest instanceof CreateElementRequestAdapter) { CreateElementRequest request = (CreateElementRequest) ((CreateElementRequestAdapter)elementRequest).getAdapter(CreateElementRequest.class); Object element = request.getNewElement(); MindFile mindFile = null; URI uri = URI.createPlatformResourceURI(interfaceInformation.getPath(), true); // Test if file existing IFile file = ModelToProjectUtil.INSTANCE.getIFile(uri); TransactionImpl transaction = new TransactionImpl(request.getEditingDomain(), false); try { transaction.start(); if (element instanceof InterfaceDefinition) { if(file != null) { mindFile = ModelToProjectUtil.INSTANCE.getCurrentMindFile(uri); ((InterfaceDefinitionCustomImpl)element).setSignature(mindFile.getQualifiedName()); } ((InterfaceDefinitionCustomImpl)element).setName(interfaceInformation.getName()); ((InterfaceDefinitionCustomImpl)element).setOptional(interfaceInformation.isOptional()); ((InterfaceDefinitionCustomImpl)element).setCollection(interfaceInformation.isCollection()); ((InterfaceDefinitionCustomImpl)element).setCollectionsize(interfaceInformation.getCollectionSize()); } transaction.commit(); }catch (InterruptedException e) { e.printStackTrace(); } catch (RollbackException e) { e.printStackTrace(); } //Refresh MindDiagramUpdateAllCommand update = new MindDiagramUpdateAllCommand(true); try { update.execute(null); } catch (ExecutionException e) { e.printStackTrace(); } } } } } antiScroll = false; } public InterfaceCreationTool(List<?> connectionTypes) { super(connectionTypes); } }
lgpl-3.0
jmecosta/sonar
sonar-graph/src/test/java/org/sonar/graph/MinimumFeedbackEdgeSetSolverTest.java
4645
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.graph; import java.util.Set; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class MinimumFeedbackEdgeSetSolverTest { @Test public void testGetFeedbackEdgesOnSimpleLoop() { DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph(); dcg.addEdge("A", "B", 3).addEdge("B", "A", 1); CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg); cycleDetector.detectCycles(); MinimumFeedbackEdgeSetSolver solver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles()); Set<Edge> feedbackEdges = solver.getEdges(); assertThat(feedbackEdges.size(), is(1)); } @Test public void testFlagFeedbackEdgesOnSimpleLoop() { DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph(); dcg.addEdge("A", "B", 3).addEdge("B", "A", 1); CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg); cycleDetector.detectCycles(); MinimumFeedbackEdgeSetSolver solver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles()); Set<Edge> feedbackEdges = solver.getEdges(); assertTrue(feedbackEdges.contains(dcg.getEdge("B", "A"))); } @Test public void testGetFeedbackEdgesOnComplexGraph() { DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph(); dcg.addEdge("A", "B", 7).addEdge("B", "C", 3).addEdge("C", "D", 1).addEdge("D", "A", 3); dcg.addEdge("B", "A", 12); CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg); cycleDetector.detectCycles(); MinimumFeedbackEdgeSetSolver solver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles()); Set<Edge> feedbackEdges = solver.getEdges(); assertThat(feedbackEdges.size(), is(1)); assertTrue(feedbackEdges.contains(dcg.getEdge("A", "B"))); } @Test public void testFlagFeedbackEdgesOnUnrelatedCycles() { DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph(); dcg.addEdge("A", "B", 7).addEdge("B", "C", 3).addEdge("C", "A", 2); dcg.addEdge("D", "E", 3).addEdge("E", "D", 5); dcg.addEdge("F", "G", 1).addEdge("G", "H", 4).addEdge("H", "F", 7); CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg); cycleDetector.detectCycles(); MinimumFeedbackEdgeSetSolver solver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles()); Set<Edge> feedbackEdges = solver.getEdges(); assertThat(feedbackEdges.size(), is(3)); assertTrue(feedbackEdges.contains(dcg.getEdge("C", "A"))); assertTrue(feedbackEdges.contains(dcg.getEdge("D", "E"))); assertTrue(feedbackEdges.contains(dcg.getEdge("F", "G"))); } @Test public void testApproximateMinimumFeedbackEdges() { DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph(); dcg.addEdge("A", "B", 5).addEdge("B", "C", 9).addEdge("C", "A", 1); dcg.addEdge("D", "B", 5).addEdge("C", "D", 7); dcg.addEdge("F", "B", 5).addEdge("C", "F", 4); CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg); cycleDetector.detectCycles(); MinimumFeedbackEdgeSetSolver minimumSolver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles()); assertThat(minimumSolver.getEdges().size(), is(1)); assertTrue(minimumSolver.getEdges().contains(dcg.getEdge("B", "C"))); MinimumFeedbackEdgeSetSolver approximateSolver = new MinimumFeedbackEdgeSetSolver(cycleDetector.getCycles(), 2); assertThat(approximateSolver.getEdges().size(), is(2)); assertTrue(approximateSolver.getEdges().contains(dcg.getEdge("B", "C"))); assertTrue(approximateSolver.getEdges().contains(dcg.getEdge("C", "A"))); } }
lgpl-3.0
claudejin/evosuite
client/src/main/java/org/evosuite/symbolic/vm/math/CBRT.java
1674
/** * Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.symbolic.vm.math; import org.evosuite.symbolic.expr.Operator; import org.evosuite.symbolic.expr.fp.RealUnaryExpression; import org.evosuite.symbolic.expr.fp.RealValue; import org.evosuite.symbolic.vm.SymbolicFunction; import org.evosuite.symbolic.vm.SymbolicEnvironment; public final class CBRT extends SymbolicFunction { private static final String CBRT = "cbrt"; public CBRT(SymbolicEnvironment env) { super(env, Types.JAVA_LANG_MATH, CBRT, Types.D2D_DESCRIPTOR); } @Override public Object executeFunction() { double res = this.getConcDoubleRetVal(); RealValue realExpression = this.getSymbRealArgument(0); RealValue cbrtExpr; if (realExpression.containsSymbolicVariable()) { Operator op = Operator.CBRT; cbrtExpr = new RealUnaryExpression(realExpression, op, res); } else { cbrtExpr = this.getSymbRealRetVal(); } return cbrtExpr; } }
lgpl-3.0
TechnicPack/MinecraftCore
src/main/java/net/technicpack/minecraftcore/mojang/version/io/LaunchArguments.java
337
package net.technicpack.minecraftcore.mojang.version.io; import net.technicpack.minecraftcore.mojang.version.io.argument.ArgumentList; public class LaunchArguments { private ArgumentList game; private ArgumentList jvm; public ArgumentList getGameArgs() { return game; } public ArgumentList getJvmArgs() { return jvm; } }
lgpl-3.0
AshwinJay/StreamCruncher
demo_src/streamcruncher/test/func/h2/H2TimeWindowFPerfTest.java
1146
package streamcruncher.test.func.h2; import java.util.List; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import streamcruncher.test.TestGroupNames; import streamcruncher.test.func.BatchResult; import streamcruncher.test.func.generic.TimeWindowFPerfTest; /* * Author: Ashwin Jayaprakash Date: Nov 12, 2006 Time: 1:26:09 PM */ public class H2TimeWindowFPerfTest extends TimeWindowFPerfTest { @Override @BeforeGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 }) public void init() throws Exception { super.init(); } @Test(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, groups = { TestGroupNames.SC_TEST_H2 }) protected void performTest() throws Exception { List<BatchResult> results = test(); } @Override @AfterGroups(dependsOnGroups = { TestGroupNames.SC_INIT_REQUIRED }, value = { TestGroupNames.SC_TEST_H2 }, groups = { TestGroupNames.SC_TEST_H2 }) public void discard() { super.discard(); } }
lgpl-3.0
green-vulcano/gv-legacy
gvlegacy/gvvcl-ws/src/main/java/it/greenvulcano/gvesb/http/ntlm/JCIFS_NTLMScheme.java
9131
/******************************************************************************* * Copyright (c) 2009, 2016 GreenVulcano ESB Open Source Project. * All rights reserved. * * This file is part of GreenVulcano ESB. * * GreenVulcano ESB is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreenVulcano ESB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GreenVulcano ESB. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package it.greenvulcano.gvesb.http.ntlm; import java.io.IOException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.httpclient.auth.AuthChallengeParser; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthenticationException; import org.apache.commons.httpclient.auth.InvalidCredentialsException; import org.apache.commons.httpclient.auth.MalformedChallengeException; /** * * This is a reimplementation of HTTPClient 3.x's * * org.apache.commons.httpclient.auth.NTLMScheme.<BR/> * * It will basically use JCIFS (v1.3.15) in order to provide added support for * * NTLMv2 (instead of trying to create its own Type, 2 and 3 messages). <BR/> * * This class has to be registered manually with HTTPClient before setting * * NTCredentials: AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, * * JCIFS_NTLMScheme.class); <BR/> * * Will <B>not</B> work with HttpClient 4.x which requires AuthEngine to be * overriden instead of AuthScheme. * * * * @author Sachin M */ /** * @version 3.3.0 22/ott/2012 * @author GreenVulcano Developer Team */ public class JCIFS_NTLMScheme implements AuthScheme { /** NTLM challenge string. */ private String ntlmchallenge = null; private static final int UNINITIATED = 0; private static final int INITIATED = 1; private static final int TYPE1_MSG_GENERATED = 2; private static final int TYPE2_MSG_RECEIVED = 3; private static final int TYPE3_MSG_GENERATED = 4; private static final int FAILED = Integer.MAX_VALUE; /** Authentication process state */ private int state; public JCIFS_NTLMScheme() throws AuthenticationException { // Check if JCIFS is present. If not present, do not proceed. try { Class.forName("jcifs.ntlmssp.NtlmMessage", false, this.getClass().getClassLoader()); } catch (ClassNotFoundException e) { throw new AuthenticationException("Unable to proceed as JCIFS library is not found."); } } @Override public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { if (this.state == UNINITIATED) { throw new IllegalStateException("NTLM authentication process has not been initiated"); } NTCredentials ntcredentials = null; try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException("Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } NTLM ntlm = new NTLM(); ntlm.setCredentialCharset(method.getParams().getCredentialCharset()); String response = null; if ((this.state == INITIATED) || (this.state == FAILED)) { response = ntlm.generateType1Msg(ntcredentials.getHost(), ntcredentials.getDomain()); this.state = TYPE1_MSG_GENERATED; } else { response = ntlm.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(), ntcredentials.getHost(), ntcredentials.getDomain(), this.ntlmchallenge); this.state = TYPE3_MSG_GENERATED; } return "NTLM " + response; } @Override public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { throw new RuntimeException("Not implemented as it is deprecated anyway in Httpclient 3.x"); } @Override public String getID() { throw new RuntimeException("Not implemented as it is deprecated anyway in Httpclient 3.x"); } /** * * Returns the authentication parameter with the given name, if available. * <p> * There are no valid parameters for NTLM authentication so this method * always returns <tt>null</tt>. * </p> * * @param name * The name of the parameter to be returned * @return the parameter with the given name */ @Override public String getParameter(String name) { if (name == null) { throw new IllegalArgumentException("Parameter name may not be null"); } return null; } /** * The concept of an authentication realm is not supported by the NTLM * authentication scheme. Always returns <code>null</code>. * * @return <code>null</code> */ @Override public String getRealm() { return null; } /** * Returns textual designation of the NTLM authentication scheme. * * @return <code>ntlm</code> */ @Override public String getSchemeName() { return "ntlm"; } /** * Tests if the NTLM authentication process has been completed. * * @return <tt>true</tt> if Basic authorization has been processed, * <tt>false</tt> otherwise. * @since 3.0 */ @Override public boolean isComplete() { return (this.state == TYPE3_MSG_GENERATED) || (this.state == FAILED); } /** * Returns <tt>true</tt>. NTLM authentication scheme is connection based. * * @return <tt>true</tt>. * @since 3.0 */ @Override public boolean isConnectionBased() { return true; } /** * Processes the NTLM challenge. * * @param challenge * the challenge string * @throws MalformedChallengeException * is thrown if the authentication challenge is malformed * @since 3.0 */ @Override public void processChallenge(final String challenge) throws MalformedChallengeException { String s = AuthChallengeParser.extractScheme(challenge); if (!s.equalsIgnoreCase(getSchemeName())) { throw new MalformedChallengeException("Invalid NTLM challenge: " + challenge); } int i = challenge.indexOf(' '); if (i != -1) { s = challenge.substring(i, challenge.length()); this.ntlmchallenge = s.trim(); this.state = TYPE2_MSG_RECEIVED; } else { this.ntlmchallenge = ""; if (this.state == UNINITIATED) { this.state = INITIATED; } else { this.state = FAILED; } } } private class NTLM { /** Character encoding */ public static final String DEFAULT_CHARSET = "ASCII"; /** * The character was used by 3.x's NTLM to encode the username and * password. Apparently, this is not needed in when passing username, * password from NTCredentials to the JCIFS library */ @SuppressWarnings("unused") private String credentialCharset = DEFAULT_CHARSET; void setCredentialCharset(String credentialCharset) { this.credentialCharset = credentialCharset; } private String generateType1Msg(String host, String domain) { jcifs.ntlmssp.Type1Message t1m = new jcifs.ntlmssp.Type1Message( jcifs.ntlmssp.Type1Message.getDefaultFlags(), domain, host); return jcifs.util.Base64.encode(t1m.toByteArray()); } private String generateType3Msg(String username, String password, String host, String domain, String challenge) { jcifs.ntlmssp.Type2Message t2m; try { t2m = new jcifs.ntlmssp.Type2Message(jcifs.util.Base64.decode(challenge)); } catch (IOException e) { throw new RuntimeException("Invalid Type2 message", e); } jcifs.ntlmssp.Type3Message t3m = new jcifs.ntlmssp.Type3Message(t2m, password, domain, username, host, 0); return jcifs.util.Base64.encode(t3m.toByteArray()); } } }
lgpl-3.0
stefanrinderle/sonar-softvis3d-plugin
src/test/java/de/rinderle/softvis3d/preprocessing/dependencies/DependencyExpanderCheckCounterTest.java
6394
/* * SoftVis3D Sonar plugin * Copyright (C) 2014 Stefan Rinderle * stefan@rinderle.info * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package de.rinderle.softvis3d.preprocessing.dependencies; import de.rinderle.softvis3d.TestTreeBuilder; import de.rinderle.softvis3d.cache.SnapshotCacheService; import de.rinderle.softvis3d.domain.sonar.SonarDependency; import de.rinderle.softvis3d.domain.tree.RootTreeNode; import de.rinderle.softvis3d.domain.tree.TreeNode; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; /** * Checks that the dependency expander creates dependency nodes and does the counting right.. */ public class DependencyExpanderCheckCounterTest { @InjectMocks private final DependencyExpander underTest = new DependencyExpander(); @Mock private SnapshotCacheService treeService; @Before public void setUp() { MockitoAnnotations.initMocks(this); } /** * * A(1) / \ B(2)-->C(3) <-- * **/ @Test public void testDependenciesFlatEdges() { final List<SonarDependency> dependencies = new ArrayList<SonarDependency>(); final SonarDependency fromBtoC = TestTreeBuilder.createDependency(2, 3); dependencies.add(fromBtoC); final SonarDependency fromCtoB = TestTreeBuilder.createDependency(3, 2); dependencies.add(fromCtoB); final RootTreeNode treeNode1 = new RootTreeNode(1); final TreeNode treeNode2 = TestTreeBuilder.createTreeNode(2, treeNode1, 1); final TreeNode treeNode3 = TestTreeBuilder.createTreeNode(3, treeNode1, 2); this.underTest.execute(treeNode1, dependencies); assertTrue(treeNode2.getEdges().containsKey("depPath_3")); assertTrue(treeNode2.getEdges().get("depPath_3").getIncludingDependenciesSize() == 1); assertTrue(treeNode3.getEdges().containsKey("depPath_2")); assertTrue(treeNode3.getEdges().get("depPath_2").getIncludingDependenciesSize() == 1); assertTrue(treeNode1.getEdges().isEmpty()); } /** * A(1) / \ B(2)-->C(3) --> * **/ @Test public void testDependenciesSameFlatEdge() { final List<SonarDependency> dependencies = new ArrayList<SonarDependency>(); final SonarDependency fromBtoC = TestTreeBuilder.createDependency(2, 3); dependencies.add(fromBtoC); dependencies.add(fromBtoC); final RootTreeNode rootTreeNode = new RootTreeNode(1); final TreeNode treeNode2 = TestTreeBuilder.createTreeNode(2, rootTreeNode, 1); final TreeNode treeNode3 = TestTreeBuilder.createTreeNode(3, rootTreeNode, 2); this.underTest.execute(rootTreeNode, dependencies); assertTrue(treeNode2.getEdges().containsKey("depPath_3")); assertTrue(treeNode2.getEdges().get("depPath_3").getIncludingDependenciesSize() == 2); assertTrue(rootTreeNode.getEdges().isEmpty()); assertTrue(treeNode3.getEdges().isEmpty()); } /** * A(1) / \ B(2) D(4) / > \ / / \ C(3)--/ E(5) -------> * **/ @Test public void testMultipleDependencyEdges() { final List<SonarDependency> dependencies = new ArrayList<SonarDependency>(); final SonarDependency fromCtoD = TestTreeBuilder.createDependency(3, 4); dependencies.add(fromCtoD); final SonarDependency fromCtoE = TestTreeBuilder.createDependency(3, 5); dependencies.add(fromCtoE); final RootTreeNode treeNode1 = new RootTreeNode(1); final TreeNode treeNode2 = TestTreeBuilder.createTreeNode(2, treeNode1, 1); final TreeNode treeNode3 = TestTreeBuilder.createTreeNode(3, treeNode2, 2); final TreeNode treeNode4 = TestTreeBuilder.createTreeNode(4, treeNode1, 1); final TreeNode treeNode5 = TestTreeBuilder.createTreeNode(5, treeNode4, 2); final TreeNode interfaceLeafNode2 = TestTreeBuilder.createInterfaceLeafNode(90, treeNode2); final TreeNode interfaceLeafNode4 = TestTreeBuilder.createInterfaceLeafNode(91, treeNode4); this.underTest.execute(treeNode1, dependencies); // dependency elevator edge start assertTrue(treeNode3.getEdges().containsKey("depPath_90")); assertTrue(treeNode3.getEdges().get("depPath_90").getIncludingDependenciesSize() == 2); // flat edge assertTrue(treeNode2.getEdges().containsKey("depPath_4")); assertTrue(treeNode2.getEdges().get("depPath_4").getIncludingDependenciesSize() == 2); // dependency elevator edge end assertTrue(interfaceLeafNode4.getEdges().containsKey("depPath_5")); assertTrue(interfaceLeafNode4.getEdges().get("depPath_5").getIncludingDependenciesSize() == 1); assertTrue(treeNode5.getEdges().isEmpty()); assertTrue(interfaceLeafNode2.getEdges().isEmpty()); } // private TreeNode createTreeNode(final int id, final TreeNode parent, final int depth) { // final TreeNode result = new TreeNode(id, parent, depth, TreeNodeType.TREE, id + ""); // // parent.addChildrenNode(id + "", result); // // return result; // } // // private TreeNode createInterfaceLeafNode(final int id, final TreeNode parent) { // final DependencyTreeNode result = new DependencyTreeNode(id, parent, parent.getDepth() + 1); // // final String intLeafLabel = DependencyExpanderBean.INTERFACE_PREFIX + "_" + parent.getId(); // // parent.addChildrenNode(intLeafLabel, result); // // return result; // } // // private SonarDependency createDependency(final int from, final int to) { // final SonarDependencyBuilder result = new SonarDependencyBuilder(); // // result.withId(new Long(from + "" + to)); // result.withFromSnapshotId(from); // result.withToSnapshotId(to); // // return result.createSonarDependency(); // } }
lgpl-3.0
armatys/hypergraphdb-android
hgdb-android/java/src/org/hypergraphdb/cache/CacheMap.java
1433
package org.hypergraphdb.cache; /** * * <p> * A simplified map interface for cache-only purposes. In addition to the simplification * this interface distinguishes two cases of addition and removal depending on whether * the data is being actually modified or just swapped in and out of memory. * </p> * It define two methods * for adding elements to the cache with different semantics: 'load' and 'put'. * The 'load' method is to be used when data is fetched from permanent storage * while the 'put' method is to be used where the data associated with a given * key is modified at runtime. This distinction is important for managing the * MVCC transactional cache - the 'load' operation is <strong>not</strong> going to * be rolled back in case of an abort! * </p> * * <p> * Similarly, it defines two methods for removing elements: 'drop' and 'remove'. The * former is analogous to load, it is to be used to free memory from the cache and its * effect is not going to be rolled back in case of a transaction abort. The latter is * for permanently removing a data item and it is going to be rolled back in case of * an abort. * </p> * * @author Borislav Iordanov * */ public interface CacheMap<K, V> { V get(K key); void put(K key, V value); void load(K key, V value); void remove(K key); void drop(K key); void clear(); int size(); }
lgpl-3.0
FenixEdu/oddjet
src/test/java/org/fenixedu/oddjet/test/bean/localeObject.java
617
package org.fenixedu.oddjet.test.bean; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class localeObject implements Serializable { private Map<Locale, Object> content = new HashMap<Locale, Object>(); public Map<Locale, Object> getContent() { return content; } public void setContent(Map<Locale, Object> content) { this.content = content; } public Object getContent(Locale l) { return content.get(l); }; public Object addContent(Locale l, Object o) { return content.put(l, o); }; }
lgpl-3.0
TKiura/GenericBroker2
GenericBroker2/src/net/agmodel/physical/AbstractUnit.java
733
/** * Code generated by ObjectDomain 2.5 using Python script "javaCodeGen 1.0" */ package net.agmodel.physical; import java.io.Serializable; abstract public class AbstractUnit implements Serializable { public String unitName; protected double Factor; public final int ord; protected AbstractUnit(String unitName,double Factor,int ord) { this.unitName=unitName; this.Factor=Factor; this.ord=ord; } public String toString() { return(unitName); } public boolean equals(Object obj) { if (!(obj instanceof AbstractUnit)) return false; else return ord==((AbstractUnit) obj).ord; } public int hashCode(){ return ord; } double getFactor() { return Factor; } }
lgpl-3.0
Spacecraft-Code/SPELL
src/spel-gui/com.astra.ses.spell.gui.sampleview/src/com/astra/ses/spell/gui/presentation/sample/SamplePresentation.java
6526
/////////////////////////////////////////////////////////////////////////////// // // PACKAGE : com.astra.ses.spell.gui.presentation.sample // // FILE : SamplePresentation.java // // DATE : 2008-11-21 08:55 // // Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.A.R.L. // // By using this software in any way, you are agreeing to be bound by // the terms of this license. // // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // which accompanies this distribution, and is available at // http://www.eclipse.org/legal/epl-v10.html // // NO WARRANTY // EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED // 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. Each Recipient is solely responsible for determining // the appropriateness of using and distributing the Program and assumes all // risks associated with its exercise of rights under this Agreement , // including but not limited to the risks and costs of program errors, // compliance with applicable laws, damage to or loss of data, programs or // equipment, and unavailability or interruption of operations. // // DISCLAIMER OF LIABILITY // EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY // CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION // LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE // EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGES. // // Contributors: // SES ENGINEERING - initial API and implementation and/or initial documentation // // PROJECT : SPELL // // SUBPROJECT: SPELL GUI Client // /////////////////////////////////////////////////////////////////////////////// package com.astra.ses.spell.gui.presentation.sample; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import com.astra.ses.spell.gui.interfaces.IPresentationNotifier; import com.astra.ses.spell.gui.interfaces.IProcedurePresentation; import com.astra.ses.spell.gui.interfaces.ProcedurePresentationAdapter; import com.astra.ses.spell.gui.procs.interfaces.model.IProcedure; public class SamplePresentation extends ProcedurePresentationAdapter implements IProcedurePresentation { /** Holds the presentation identifier */ private static final String ID = "com.astra.ses.spell.gui.presentation.Sample"; /** Holds the presentation title */ private static final String PRESENTATION_TITLE = "Sample"; /** Holds the presentation description */ private static final String PRESENTATION_DESC = "Sample procedure view"; /** Holds the presentation icon */ private static final String PRESENTATION_ICON = "icons/16x16/asterisk.png"; /** Parent view */ private IProcedure m_model; /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#createContents * (IProcedure,Composite) */ @Override public Composite createContents(IProcedure model, Composite stack) { m_model = model; Composite shellPage = new Composite(stack, SWT.NONE); GridLayout groupLayout = new GridLayout(); groupLayout.marginHeight = 0; groupLayout.marginWidth = 0; groupLayout.marginBottom = 0; groupLayout.marginTop = 0; groupLayout.verticalSpacing = 0; groupLayout.numColumns = 1; shellPage.setLayout(groupLayout); GridData data = new GridData(); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; data.verticalAlignment = SWT.FILL; shellPage.setLayoutData(data); // TODO create the page contents on the shellPage composite return shellPage; } /* * (non-Javadoc) * * @see com.astra.ses.spell.gui.interfaces.IProcedurePresentation# * subscribeNotifications(IPresentationNotifier) */ @Override public void subscribeNotifications(IPresentationNotifier notifier) { // TODO subscribe to the interesting events in the notifier using // listener mechanism } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#getExtensionId * (boolean) */ @Override public String getExtensionId() { return ID; } /* * (non-Javadoc) * * @see com.astra.ses.spell.gui.interfaces.IProcedurePresentation#getTitle() */ @Override public String getTitle() { return PRESENTATION_TITLE; } /* * (non-Javadoc) * * @see com.astra.ses.spell.gui.interfaces.IProcedurePresentation#getIcon() */ @Override public Image getIcon() { return Activator.getImageDescriptor(PRESENTATION_ICON).createImage(); } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#getDescription * () */ @Override public String getDescription() { return PRESENTATION_DESC; } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#zoom(boolean) */ @Override public void zoom(boolean zoomIn) { } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#showLine(int) */ @Override public void showLine(int lineNo) { } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#setAutoScroll * (boolean) */ @Override public void setAutoScroll(boolean enabled) { } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#setEnabled( * boolean) */ @Override public void setEnabled(boolean enabled) { } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#getAdapter( * class) */ @Override public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { return null; } /* * (non-Javadoc) * * @see * com.astra.ses.spell.gui.interfaces.IProcedurePresentation#setSelected * (boolean) */ @Override public void setSelected(boolean selected) { // TODO Auto-generated method stub } }
lgpl-3.0
tunguski/matsuo-core
matsuo-core/src/test/java/pl/matsuo/core/test/TestAbstractPrintTest.java
472
package pl.matsuo.core.test; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestAbstractPrintTest { @Test public void testLookupTestName() { AbstractPrintTest abstractPrintTest = new AbstractPrintTest() { @Override protected String getPrintFileName() { return "/prints/test.ftl"; } }; assertEquals("testLookupTestName", abstractPrintTest.lookupTestName()); } }
lgpl-3.0
ideaconsult/i5
iuclid_6_2-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_crystallinephase/_2/ENDPOINTSTUDYRECORDCrystallinePhase.java
141820
package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_crystallinephase._2; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.AttachmentListField; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.DataProtectionField; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.DocumentReferenceMultipleField; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistField; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistFieldWithLargeTextRemarks; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistFieldWithMultiLineTextRemarks; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.PicklistFieldWithSmallTextRemarks; import eu.europa.echa.iuclid6.namespaces.platform_fields.v1.RepeatableEntryType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="AdministrativeData"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DataProtection" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}dataProtectionField"/> * &lt;element name="Endpoint" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="StudyResultType" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="PurposeFlag" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="RobustStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="UsedForClassification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="UsedForMSDS" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="StudyPeriod" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;element name="Reliability" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="RationalReliability" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithLargeTextRemarks"/> * &lt;element name="DataWaiving" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="DataWaivingJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithLargeTextRemarks" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="JustificationForTypeOfInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="AttachedJustification"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="CrossReference"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="RelatedInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="DataSource"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Reference" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceMultipleField"/> * &lt;element name="DataAccess" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="DataProtectionClaimed" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="MaterialsAndMethods"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Guideline"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="Qualifier" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="Guideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="VersionRemarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="Deviation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="MethodNoGuideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="GLPComplianceStatement" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="OtherQualityAssurance" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="MethodType" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="DetailsOnMethodsAndDataEvaluation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Sampling" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="TestMaterials"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TestMaterialInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SpecificDetailsOnTestMaterialUsedForTheStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="ReferenceMaterial"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReferenceMaterialNanomaterial" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SampleIdentificationNumber" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="DataGathering"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Instruments" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Calibration" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Reproducibility" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="AnyOtherInformationOnMaterialsAndMethodsInclTables"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="ResultsAndDiscussion"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CrystallinePhase"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="KeyResult" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="CommonName" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystalSystem" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="BravaisLattice" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="PointGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="SpaceGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystallographicPlanes" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithMultiLineTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="CrystallographicComposition" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;element name="AnyOtherInformationOnResultsInclTables"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="OverallRemarksAttachments"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;element name="AttachedBackgroundMaterial"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedDocument" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="AttachedStudyReport" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentListField"/> * &lt;element name="IllustrationPicGraph" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="ApplicantSummaryAndConclusion"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Conclusions" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="ExecutiveSummary" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "administrativeData", "dataSource", "materialsAndMethods", "resultsAndDiscussion", "overallRemarksAttachments", "applicantSummaryAndConclusion" }) @XmlRootElement(name = "ENDPOINT_STUDY_RECORD.CrystallinePhase") public class ENDPOINTSTUDYRECORDCrystallinePhase { @XmlElement(name = "AdministrativeData", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData administrativeData; @XmlElement(name = "DataSource", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.DataSource dataSource; @XmlElement(name = "MaterialsAndMethods", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods materialsAndMethods; @XmlElement(name = "ResultsAndDiscussion", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion resultsAndDiscussion; @XmlElement(name = "OverallRemarksAttachments", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments overallRemarksAttachments; @XmlElement(name = "ApplicantSummaryAndConclusion", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.ApplicantSummaryAndConclusion applicantSummaryAndConclusion; /** * Gets the value of the administrativeData property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData getAdministrativeData() { return administrativeData; } /** * Sets the value of the administrativeData property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData } * */ public void setAdministrativeData(ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData value) { this.administrativeData = value; } /** * Gets the value of the dataSource property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.DataSource } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.DataSource getDataSource() { return dataSource; } /** * Sets the value of the dataSource property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.DataSource } * */ public void setDataSource(ENDPOINTSTUDYRECORDCrystallinePhase.DataSource value) { this.dataSource = value; } /** * Gets the value of the materialsAndMethods property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods getMaterialsAndMethods() { return materialsAndMethods; } /** * Sets the value of the materialsAndMethods property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods } * */ public void setMaterialsAndMethods(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods value) { this.materialsAndMethods = value; } /** * Gets the value of the resultsAndDiscussion property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion getResultsAndDiscussion() { return resultsAndDiscussion; } /** * Sets the value of the resultsAndDiscussion property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion } * */ public void setResultsAndDiscussion(ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion value) { this.resultsAndDiscussion = value; } /** * Gets the value of the overallRemarksAttachments property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments getOverallRemarksAttachments() { return overallRemarksAttachments; } /** * Sets the value of the overallRemarksAttachments property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments } * */ public void setOverallRemarksAttachments(ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments value) { this.overallRemarksAttachments = value; } /** * Gets the value of the applicantSummaryAndConclusion property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ApplicantSummaryAndConclusion } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.ApplicantSummaryAndConclusion getApplicantSummaryAndConclusion() { return applicantSummaryAndConclusion; } /** * Sets the value of the applicantSummaryAndConclusion property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ApplicantSummaryAndConclusion } * */ public void setApplicantSummaryAndConclusion(ENDPOINTSTUDYRECORDCrystallinePhase.ApplicantSummaryAndConclusion value) { this.applicantSummaryAndConclusion = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DataProtection" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}dataProtectionField"/> * &lt;element name="Endpoint" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="StudyResultType" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="PurposeFlag" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="RobustStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="UsedForClassification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="UsedForMSDS" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="StudyPeriod" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;element name="Reliability" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="RationalReliability" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithLargeTextRemarks"/> * &lt;element name="DataWaiving" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="DataWaivingJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithLargeTextRemarks" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="JustificationForTypeOfInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="AttachedJustification"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="CrossReference"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="RelatedInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "dataProtection", "endpoint", "studyResultType", "purposeFlag", "robustStudy", "usedForClassification", "usedForMSDS", "studyPeriod", "reliability", "rationalReliability", "dataWaiving", "dataWaivingJustification", "justificationForTypeOfInformation", "attachedJustification", "crossReference" }) public static class AdministrativeData { @XmlElement(name = "DataProtection", required = true) protected DataProtectionField dataProtection; @XmlElement(name = "Endpoint", required = true) protected PicklistFieldWithSmallTextRemarks endpoint; @XmlElement(name = "StudyResultType", required = true) protected PicklistFieldWithSmallTextRemarks studyResultType; @XmlElement(name = "PurposeFlag", required = true) protected PicklistField purposeFlag; @XmlElement(name = "RobustStudy", required = true, type = Boolean.class, nillable = true) protected Boolean robustStudy; @XmlElement(name = "UsedForClassification", required = true, type = Boolean.class, nillable = true) protected Boolean usedForClassification; @XmlElement(name = "UsedForMSDS", required = true, type = Boolean.class, nillable = true) protected Boolean usedForMSDS; @XmlElement(name = "StudyPeriod", required = true) protected String studyPeriod; @XmlElement(name = "Reliability", required = true) protected PicklistField reliability; @XmlElement(name = "RationalReliability", required = true) protected PicklistFieldWithLargeTextRemarks rationalReliability; @XmlElement(name = "DataWaiving", required = true) protected PicklistField dataWaiving; @XmlElement(name = "DataWaivingJustification") protected List<PicklistFieldWithLargeTextRemarks> dataWaivingJustification; @XmlElement(name = "JustificationForTypeOfInformation", required = true) protected String justificationForTypeOfInformation; @XmlElement(name = "AttachedJustification", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification attachedJustification; @XmlElement(name = "CrossReference", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference crossReference; /** * Gets the value of the dataProtection property. * * @return * possible object is * {@link DataProtectionField } * */ public DataProtectionField getDataProtection() { return dataProtection; } /** * Sets the value of the dataProtection property. * * @param value * allowed object is * {@link DataProtectionField } * */ public void setDataProtection(DataProtectionField value) { this.dataProtection = value; } /** * Gets the value of the endpoint property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getEndpoint() { return endpoint; } /** * Sets the value of the endpoint property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setEndpoint(PicklistFieldWithSmallTextRemarks value) { this.endpoint = value; } /** * Gets the value of the studyResultType property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getStudyResultType() { return studyResultType; } /** * Sets the value of the studyResultType property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setStudyResultType(PicklistFieldWithSmallTextRemarks value) { this.studyResultType = value; } /** * Gets the value of the purposeFlag property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getPurposeFlag() { return purposeFlag; } /** * Sets the value of the purposeFlag property. * * @param value * allowed object is * {@link PicklistField } * */ public void setPurposeFlag(PicklistField value) { this.purposeFlag = value; } /** * Gets the value of the robustStudy property. * * @return * possible object is * {@link Boolean } * */ public Boolean getRobustStudy() { return robustStudy; } /** * Sets the value of the robustStudy property. * * @param value * allowed object is * {@link Boolean } * */ public void setRobustStudy(Boolean value) { this.robustStudy = value; } /** * Gets the value of the usedForClassification property. * * @return * possible object is * {@link Boolean } * */ public Boolean getUsedForClassification() { return usedForClassification; } /** * Sets the value of the usedForClassification property. * * @param value * allowed object is * {@link Boolean } * */ public void setUsedForClassification(Boolean value) { this.usedForClassification = value; } /** * Gets the value of the usedForMSDS property. * * @return * possible object is * {@link Boolean } * */ public Boolean getUsedForMSDS() { return usedForMSDS; } /** * Sets the value of the usedForMSDS property. * * @param value * allowed object is * {@link Boolean } * */ public void setUsedForMSDS(Boolean value) { this.usedForMSDS = value; } /** * Gets the value of the studyPeriod property. * * @return * possible object is * {@link String } * */ public String getStudyPeriod() { return studyPeriod; } /** * Sets the value of the studyPeriod property. * * @param value * allowed object is * {@link String } * */ public void setStudyPeriod(String value) { this.studyPeriod = value; } /** * Gets the value of the reliability property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getReliability() { return reliability; } /** * Sets the value of the reliability property. * * @param value * allowed object is * {@link PicklistField } * */ public void setReliability(PicklistField value) { this.reliability = value; } /** * Gets the value of the rationalReliability property. * * @return * possible object is * {@link PicklistFieldWithLargeTextRemarks } * */ public PicklistFieldWithLargeTextRemarks getRationalReliability() { return rationalReliability; } /** * Sets the value of the rationalReliability property. * * @param value * allowed object is * {@link PicklistFieldWithLargeTextRemarks } * */ public void setRationalReliability(PicklistFieldWithLargeTextRemarks value) { this.rationalReliability = value; } /** * Gets the value of the dataWaiving property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getDataWaiving() { return dataWaiving; } /** * Sets the value of the dataWaiving property. * * @param value * allowed object is * {@link PicklistField } * */ public void setDataWaiving(PicklistField value) { this.dataWaiving = value; } /** * Gets the value of the dataWaivingJustification property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dataWaivingJustification property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDataWaivingJustification().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PicklistFieldWithLargeTextRemarks } * * */ public List<PicklistFieldWithLargeTextRemarks> getDataWaivingJustification() { if (dataWaivingJustification == null) { dataWaivingJustification = new ArrayList<PicklistFieldWithLargeTextRemarks>(); } return this.dataWaivingJustification; } /** * Gets the value of the justificationForTypeOfInformation property. * * @return * possible object is * {@link String } * */ public String getJustificationForTypeOfInformation() { return justificationForTypeOfInformation; } /** * Sets the value of the justificationForTypeOfInformation property. * * @param value * allowed object is * {@link String } * */ public void setJustificationForTypeOfInformation(String value) { this.justificationForTypeOfInformation = value; } /** * Gets the value of the attachedJustification property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification getAttachedJustification() { return attachedJustification; } /** * Sets the value of the attachedJustification property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification } * */ public void setAttachedJustification(ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification value) { this.attachedJustification = value; } /** * Gets the value of the crossReference property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference getCrossReference() { return crossReference; } /** * Sets the value of the crossReference property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference } * */ public void setCrossReference(ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference value) { this.crossReference = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class AttachedJustification { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.AttachedJustification.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedJustification" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "attachedJustification", "reasonPurpose" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "AttachedJustification", required = true) protected String attachedJustification; @XmlElement(name = "ReasonPurpose", required = true) protected PicklistFieldWithSmallTextRemarks reasonPurpose; /** * Gets the value of the attachedJustification property. * * @return * possible object is * {@link String } * */ public String getAttachedJustification() { return attachedJustification; } /** * Sets the value of the attachedJustification property. * * @param value * allowed object is * {@link String } * */ public void setAttachedJustification(String value) { this.attachedJustification = value; } /** * Gets the value of the reasonPurpose property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getReasonPurpose() { return reasonPurpose; } /** * Sets the value of the reasonPurpose property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setReasonPurpose(PicklistFieldWithSmallTextRemarks value) { this.reasonPurpose = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="RelatedInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class CrossReference { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.AdministrativeData.CrossReference.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReasonPurpose" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="RelatedInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "reasonPurpose", "relatedInformation", "remarks" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "ReasonPurpose", required = true) protected PicklistFieldWithSmallTextRemarks reasonPurpose; @XmlElement(name = "RelatedInformation", required = true) protected String relatedInformation; @XmlElement(name = "Remarks", required = true) protected String remarks; /** * Gets the value of the reasonPurpose property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getReasonPurpose() { return reasonPurpose; } /** * Sets the value of the reasonPurpose property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setReasonPurpose(PicklistFieldWithSmallTextRemarks value) { this.reasonPurpose = value; } /** * Gets the value of the relatedInformation property. * * @return * possible object is * {@link String } * */ public String getRelatedInformation() { return relatedInformation; } /** * Sets the value of the relatedInformation property. * * @param value * allowed object is * {@link String } * */ public void setRelatedInformation(String value) { this.relatedInformation = value; } /** * Gets the value of the remarks property. * * @return * possible object is * {@link String } * */ public String getRemarks() { return remarks; } /** * Sets the value of the remarks property. * * @param value * allowed object is * {@link String } * */ public void setRemarks(String value) { this.remarks = value; } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Conclusions" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="ExecutiveSummary" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "conclusions", "executiveSummary" }) public static class ApplicantSummaryAndConclusion { @XmlElement(name = "Conclusions", required = true) protected String conclusions; @XmlElement(name = "ExecutiveSummary", required = true) protected String executiveSummary; /** * Gets the value of the conclusions property. * * @return * possible object is * {@link String } * */ public String getConclusions() { return conclusions; } /** * Sets the value of the conclusions property. * * @param value * allowed object is * {@link String } * */ public void setConclusions(String value) { this.conclusions = value; } /** * Gets the value of the executiveSummary property. * * @return * possible object is * {@link String } * */ public String getExecutiveSummary() { return executiveSummary; } /** * Sets the value of the executiveSummary property. * * @param value * allowed object is * {@link String } * */ public void setExecutiveSummary(String value) { this.executiveSummary = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Reference" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceMultipleField"/> * &lt;element name="DataAccess" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="DataProtectionClaimed" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "reference", "dataAccess", "dataProtectionClaimed" }) public static class DataSource { @XmlElement(name = "Reference", required = true) protected DocumentReferenceMultipleField reference; @XmlElement(name = "DataAccess", required = true) protected PicklistFieldWithSmallTextRemarks dataAccess; @XmlElement(name = "DataProtectionClaimed", required = true) protected PicklistFieldWithSmallTextRemarks dataProtectionClaimed; /** * Gets the value of the reference property. * * @return * possible object is * {@link DocumentReferenceMultipleField } * */ public DocumentReferenceMultipleField getReference() { return reference; } /** * Sets the value of the reference property. * * @param value * allowed object is * {@link DocumentReferenceMultipleField } * */ public void setReference(DocumentReferenceMultipleField value) { this.reference = value; } /** * Gets the value of the dataAccess property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getDataAccess() { return dataAccess; } /** * Sets the value of the dataAccess property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setDataAccess(PicklistFieldWithSmallTextRemarks value) { this.dataAccess = value; } /** * Gets the value of the dataProtectionClaimed property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getDataProtectionClaimed() { return dataProtectionClaimed; } /** * Sets the value of the dataProtectionClaimed property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setDataProtectionClaimed(PicklistFieldWithSmallTextRemarks value) { this.dataProtectionClaimed = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Guideline"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="Qualifier" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="Guideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="VersionRemarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="Deviation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="MethodNoGuideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="GLPComplianceStatement" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="OtherQualityAssurance" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="MethodType" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="DetailsOnMethodsAndDataEvaluation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Sampling" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="TestMaterials"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TestMaterialInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SpecificDetailsOnTestMaterialUsedForTheStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="ReferenceMaterial"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReferenceMaterialNanomaterial" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SampleIdentificationNumber" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="DataGathering"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Instruments" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Calibration" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Reproducibility" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="AnyOtherInformationOnMaterialsAndMethodsInclTables"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "guideline", "methodNoGuideline", "glpComplianceStatement", "otherQualityAssurance", "methodType", "detailsOnMethodsAndDataEvaluation", "sampling", "testMaterials", "dataGathering", "anyOtherInformationOnMaterialsAndMethodsInclTables" }) public static class MaterialsAndMethods { @XmlElement(name = "Guideline", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline guideline; @XmlElement(name = "MethodNoGuideline", required = true) protected String methodNoGuideline; @XmlElement(name = "GLPComplianceStatement", required = true) protected PicklistFieldWithSmallTextRemarks glpComplianceStatement; @XmlElement(name = "OtherQualityAssurance", required = true) protected PicklistFieldWithSmallTextRemarks otherQualityAssurance; @XmlElement(name = "MethodType", required = true) protected PicklistFieldWithSmallTextRemarks methodType; @XmlElement(name = "DetailsOnMethodsAndDataEvaluation", required = true) protected String detailsOnMethodsAndDataEvaluation; @XmlElement(name = "Sampling", required = true) protected String sampling; @XmlElement(name = "TestMaterials", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials testMaterials; @XmlElement(name = "DataGathering", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.DataGathering dataGathering; @XmlElement(name = "AnyOtherInformationOnMaterialsAndMethodsInclTables", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables anyOtherInformationOnMaterialsAndMethodsInclTables; /** * Gets the value of the guideline property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline getGuideline() { return guideline; } /** * Sets the value of the guideline property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline } * */ public void setGuideline(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline value) { this.guideline = value; } /** * Gets the value of the methodNoGuideline property. * * @return * possible object is * {@link String } * */ public String getMethodNoGuideline() { return methodNoGuideline; } /** * Sets the value of the methodNoGuideline property. * * @param value * allowed object is * {@link String } * */ public void setMethodNoGuideline(String value) { this.methodNoGuideline = value; } /** * Gets the value of the glpComplianceStatement property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getGLPComplianceStatement() { return glpComplianceStatement; } /** * Sets the value of the glpComplianceStatement property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setGLPComplianceStatement(PicklistFieldWithSmallTextRemarks value) { this.glpComplianceStatement = value; } /** * Gets the value of the otherQualityAssurance property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getOtherQualityAssurance() { return otherQualityAssurance; } /** * Sets the value of the otherQualityAssurance property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setOtherQualityAssurance(PicklistFieldWithSmallTextRemarks value) { this.otherQualityAssurance = value; } /** * Gets the value of the methodType property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getMethodType() { return methodType; } /** * Sets the value of the methodType property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setMethodType(PicklistFieldWithSmallTextRemarks value) { this.methodType = value; } /** * Gets the value of the detailsOnMethodsAndDataEvaluation property. * * @return * possible object is * {@link String } * */ public String getDetailsOnMethodsAndDataEvaluation() { return detailsOnMethodsAndDataEvaluation; } /** * Sets the value of the detailsOnMethodsAndDataEvaluation property. * * @param value * allowed object is * {@link String } * */ public void setDetailsOnMethodsAndDataEvaluation(String value) { this.detailsOnMethodsAndDataEvaluation = value; } /** * Gets the value of the sampling property. * * @return * possible object is * {@link String } * */ public String getSampling() { return sampling; } /** * Sets the value of the sampling property. * * @param value * allowed object is * {@link String } * */ public void setSampling(String value) { this.sampling = value; } /** * Gets the value of the testMaterials property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials getTestMaterials() { return testMaterials; } /** * Sets the value of the testMaterials property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials } * */ public void setTestMaterials(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials value) { this.testMaterials = value; } /** * Gets the value of the dataGathering property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.DataGathering } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.DataGathering getDataGathering() { return dataGathering; } /** * Sets the value of the dataGathering property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.DataGathering } * */ public void setDataGathering(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.DataGathering value) { this.dataGathering = value; } /** * Gets the value of the anyOtherInformationOnMaterialsAndMethodsInclTables property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables getAnyOtherInformationOnMaterialsAndMethodsInclTables() { return anyOtherInformationOnMaterialsAndMethodsInclTables; } /** * Sets the value of the anyOtherInformationOnMaterialsAndMethodsInclTables property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables } * */ public void setAnyOtherInformationOnMaterialsAndMethodsInclTables(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables value) { this.anyOtherInformationOnMaterialsAndMethodsInclTables = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "otherInformation" }) public static class AnyOtherInformationOnMaterialsAndMethodsInclTables { @XmlElement(name = "OtherInformation", required = true) protected String otherInformation; /** * Gets the value of the otherInformation property. * * @return * possible object is * {@link String } * */ public String getOtherInformation() { return otherInformation; } /** * Sets the value of the otherInformation property. * * @param value * allowed object is * {@link String } * */ public void setOtherInformation(String value) { this.otherInformation = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Instruments" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Calibration" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="Reproducibility" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "instruments", "calibration", "reproducibility" }) public static class DataGathering { @XmlElement(name = "Instruments", required = true) protected String instruments; @XmlElement(name = "Calibration", required = true) protected String calibration; @XmlElement(name = "Reproducibility", required = true) protected String reproducibility; /** * Gets the value of the instruments property. * * @return * possible object is * {@link String } * */ public String getInstruments() { return instruments; } /** * Sets the value of the instruments property. * * @param value * allowed object is * {@link String } * */ public void setInstruments(String value) { this.instruments = value; } /** * Gets the value of the calibration property. * * @return * possible object is * {@link String } * */ public String getCalibration() { return calibration; } /** * Sets the value of the calibration property. * * @param value * allowed object is * {@link String } * */ public void setCalibration(String value) { this.calibration = value; } /** * Gets the value of the reproducibility property. * * @return * possible object is * {@link String } * */ public String getReproducibility() { return reproducibility; } /** * Sets the value of the reproducibility property. * * @param value * allowed object is * {@link String } * */ public void setReproducibility(String value) { this.reproducibility = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="Qualifier" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="Guideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="VersionRemarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="Deviation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class Guideline { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.Guideline.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="Qualifier" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="Guideline" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="VersionRemarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="Deviation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "qualifier", "guideline", "versionRemarks", "deviation" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "Qualifier", required = true) protected PicklistField qualifier; @XmlElement(name = "Guideline", required = true) protected PicklistField guideline; @XmlElement(name = "VersionRemarks", required = true) protected String versionRemarks; @XmlElement(name = "Deviation", required = true) protected PicklistFieldWithSmallTextRemarks deviation; /** * Gets the value of the qualifier property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getQualifier() { return qualifier; } /** * Sets the value of the qualifier property. * * @param value * allowed object is * {@link PicklistField } * */ public void setQualifier(PicklistField value) { this.qualifier = value; } /** * Gets the value of the guideline property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getGuideline() { return guideline; } /** * Sets the value of the guideline property. * * @param value * allowed object is * {@link PicklistField } * */ public void setGuideline(PicklistField value) { this.guideline = value; } /** * Gets the value of the versionRemarks property. * * @return * possible object is * {@link String } * */ public String getVersionRemarks() { return versionRemarks; } /** * Sets the value of the versionRemarks property. * * @param value * allowed object is * {@link String } * */ public void setVersionRemarks(String value) { this.versionRemarks = value; } /** * Gets the value of the deviation property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getDeviation() { return deviation; } /** * Sets the value of the deviation property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setDeviation(PicklistFieldWithSmallTextRemarks value) { this.deviation = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TestMaterialInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SpecificDetailsOnTestMaterialUsedForTheStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/> * &lt;element name="ReferenceMaterial"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReferenceMaterialNanomaterial" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SampleIdentificationNumber" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "testMaterialInformation", "specificDetailsOnTestMaterialUsedForTheStudy", "referenceMaterial" }) public static class TestMaterials { @XmlElement(name = "TestMaterialInformation", required = true) protected String testMaterialInformation; @XmlElement(name = "SpecificDetailsOnTestMaterialUsedForTheStudy", required = true) protected String specificDetailsOnTestMaterialUsedForTheStudy; @XmlElement(name = "ReferenceMaterial", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial referenceMaterial; /** * Gets the value of the testMaterialInformation property. * * @return * possible object is * {@link String } * */ public String getTestMaterialInformation() { return testMaterialInformation; } /** * Sets the value of the testMaterialInformation property. * * @param value * allowed object is * {@link String } * */ public void setTestMaterialInformation(String value) { this.testMaterialInformation = value; } /** * Gets the value of the specificDetailsOnTestMaterialUsedForTheStudy property. * * @return * possible object is * {@link String } * */ public String getSpecificDetailsOnTestMaterialUsedForTheStudy() { return specificDetailsOnTestMaterialUsedForTheStudy; } /** * Sets the value of the specificDetailsOnTestMaterialUsedForTheStudy property. * * @param value * allowed object is * {@link String } * */ public void setSpecificDetailsOnTestMaterialUsedForTheStudy(String value) { this.specificDetailsOnTestMaterialUsedForTheStudy = value; } /** * Gets the value of the referenceMaterial property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial getReferenceMaterial() { return referenceMaterial; } /** * Sets the value of the referenceMaterial property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial } * */ public void setReferenceMaterial(ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial value) { this.referenceMaterial = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReferenceMaterialNanomaterial" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SampleIdentificationNumber" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class ReferenceMaterial { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.MaterialsAndMethods.TestMaterials.ReferenceMaterial.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="ReferenceMaterialNanomaterial" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/> * &lt;element name="SampleIdentificationNumber" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "referenceMaterialNanomaterial", "sampleIdentificationNumber" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "ReferenceMaterialNanomaterial", required = true) protected String referenceMaterialNanomaterial; @XmlElement(name = "SampleIdentificationNumber", required = true) protected String sampleIdentificationNumber; /** * Gets the value of the referenceMaterialNanomaterial property. * * @return * possible object is * {@link String } * */ public String getReferenceMaterialNanomaterial() { return referenceMaterialNanomaterial; } /** * Sets the value of the referenceMaterialNanomaterial property. * * @param value * allowed object is * {@link String } * */ public void setReferenceMaterialNanomaterial(String value) { this.referenceMaterialNanomaterial = value; } /** * Gets the value of the sampleIdentificationNumber property. * * @return * possible object is * {@link String } * */ public String getSampleIdentificationNumber() { return sampleIdentificationNumber; } /** * Sets the value of the sampleIdentificationNumber property. * * @param value * allowed object is * {@link String } * */ public void setSampleIdentificationNumber(String value) { this.sampleIdentificationNumber = value; } } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;element name="AttachedBackgroundMaterial"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedDocument" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="AttachedStudyReport" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentListField"/> * &lt;element name="IllustrationPicGraph" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "remarksOnResults", "attachedBackgroundMaterial", "attachedStudyReport", "illustrationPicGraph" }) public static class OverallRemarksAttachments { @XmlElement(name = "RemarksOnResults", required = true) protected String remarksOnResults; @XmlElement(name = "AttachedBackgroundMaterial", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial attachedBackgroundMaterial; @XmlElement(name = "AttachedStudyReport", required = true) protected AttachmentListField attachedStudyReport; @XmlElement(name = "IllustrationPicGraph", required = true) protected String illustrationPicGraph; /** * Gets the value of the remarksOnResults property. * * @return * possible object is * {@link String } * */ public String getRemarksOnResults() { return remarksOnResults; } /** * Sets the value of the remarksOnResults property. * * @param value * allowed object is * {@link String } * */ public void setRemarksOnResults(String value) { this.remarksOnResults = value; } /** * Gets the value of the attachedBackgroundMaterial property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial getAttachedBackgroundMaterial() { return attachedBackgroundMaterial; } /** * Sets the value of the attachedBackgroundMaterial property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial } * */ public void setAttachedBackgroundMaterial(ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial value) { this.attachedBackgroundMaterial = value; } /** * Gets the value of the attachedStudyReport property. * * @return * possible object is * {@link AttachmentListField } * */ public AttachmentListField getAttachedStudyReport() { return attachedStudyReport; } /** * Sets the value of the attachedStudyReport property. * * @param value * allowed object is * {@link AttachmentListField } * */ public void setAttachedStudyReport(AttachmentListField value) { this.attachedStudyReport = value; } /** * Gets the value of the illustrationPicGraph property. * * @return * possible object is * {@link String } * */ public String getIllustrationPicGraph() { return illustrationPicGraph; } /** * Sets the value of the illustrationPicGraph property. * * @param value * allowed object is * {@link String } * */ public void setIllustrationPicGraph(String value) { this.illustrationPicGraph = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedDocument" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class AttachedBackgroundMaterial { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="AttachedDocument" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}attachmentField"/> * &lt;element name="Remarks" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldSmall"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "attachedDocument", "remarks" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "AttachedDocument", required = true) protected String attachedDocument; @XmlElement(name = "Remarks", required = true) protected String remarks; /** * Gets the value of the attachedDocument property. * * @return * possible object is * {@link String } * */ public String getAttachedDocument() { return attachedDocument; } /** * Sets the value of the attachedDocument property. * * @param value * allowed object is * {@link String } * */ public void setAttachedDocument(String value) { this.attachedDocument = value; } /** * Gets the value of the remarks property. * * @return * possible object is * {@link String } * */ public String getRemarks() { return remarks; } /** * Sets the value of the remarks property. * * @param value * allowed object is * {@link String } * */ public void setRemarks(String value) { this.remarks = value; } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CrystallinePhase"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="KeyResult" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="CommonName" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystalSystem" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="BravaisLattice" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="PointGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="SpaceGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystallographicPlanes" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithMultiLineTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="CrystallographicComposition" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;element name="AnyOtherInformationOnResultsInclTables"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "crystallinePhase", "crystallographicComposition", "anyOtherInformationOnResultsInclTables" }) public static class ResultsAndDiscussion { @XmlElement(name = "CrystallinePhase", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase crystallinePhase; @XmlElement(name = "CrystallographicComposition", required = true) protected String crystallographicComposition; @XmlElement(name = "AnyOtherInformationOnResultsInclTables", required = true) protected ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables anyOtherInformationOnResultsInclTables; /** * Gets the value of the crystallinePhase property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase getCrystallinePhase() { return crystallinePhase; } /** * Sets the value of the crystallinePhase property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase } * */ public void setCrystallinePhase(ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase value) { this.crystallinePhase = value; } /** * Gets the value of the crystallographicComposition property. * * @return * possible object is * {@link String } * */ public String getCrystallographicComposition() { return crystallographicComposition; } /** * Sets the value of the crystallographicComposition property. * * @param value * allowed object is * {@link String } * */ public void setCrystallographicComposition(String value) { this.crystallographicComposition = value; } /** * Gets the value of the anyOtherInformationOnResultsInclTables property. * * @return * possible object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables } * */ public ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables getAnyOtherInformationOnResultsInclTables() { return anyOtherInformationOnResultsInclTables; } /** * Sets the value of the anyOtherInformationOnResultsInclTables property. * * @param value * allowed object is * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables } * */ public void setAnyOtherInformationOnResultsInclTables(ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables value) { this.anyOtherInformationOnResultsInclTables = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OtherInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textField"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "otherInformation" }) public static class AnyOtherInformationOnResultsInclTables { @XmlElement(name = "OtherInformation", required = true) protected String otherInformation; /** * Gets the value of the otherInformation property. * * @return * possible object is * {@link String } * */ public String getOtherInformation() { return otherInformation; } /** * Sets the value of the otherInformation property. * * @param value * allowed object is * {@link String } * */ public void setOtherInformation(String value) { this.otherInformation = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entry" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="KeyResult" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="CommonName" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystalSystem" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="BravaisLattice" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="PointGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="SpaceGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystallographicPlanes" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithMultiLineTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry" }) public static class CrystallinePhase { protected List<ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase.Entry> entry; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase.Entry } * * */ public List<ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase.Entry> getEntry() { if (entry == null) { entry = new ArrayList<ENDPOINTSTUDYRECORDCrystallinePhase.ResultsAndDiscussion.CrystallinePhase.Entry>(); } return this.entry; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}repeatableEntryType"> * &lt;sequence> * &lt;element name="KeyResult" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}booleanField"/> * &lt;element name="CommonName" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystalSystem" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithSmallTextRemarks"/> * &lt;element name="BravaisLattice" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistField"/> * &lt;element name="PointGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="SpaceGroup" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="CrystallographicPlanes" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldMultiLine"/> * &lt;element name="RemarksOnResults" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}picklistFieldWithMultiLineTextRemarks"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "keyResult", "commonName", "crystalSystem", "bravaisLattice", "pointGroup", "spaceGroup", "crystallographicPlanes", "remarksOnResults" }) public static class Entry extends RepeatableEntryType { @XmlElement(name = "KeyResult", required = true, type = Boolean.class, nillable = true) protected Boolean keyResult; @XmlElement(name = "CommonName", required = true) protected String commonName; @XmlElement(name = "CrystalSystem", required = true) protected PicklistFieldWithSmallTextRemarks crystalSystem; @XmlElement(name = "BravaisLattice", required = true) protected PicklistField bravaisLattice; @XmlElement(name = "PointGroup", required = true) protected String pointGroup; @XmlElement(name = "SpaceGroup", required = true) protected String spaceGroup; @XmlElement(name = "CrystallographicPlanes", required = true) protected String crystallographicPlanes; @XmlElement(name = "RemarksOnResults", required = true) protected PicklistFieldWithMultiLineTextRemarks remarksOnResults; /** * Gets the value of the keyResult property. * * @return * possible object is * {@link Boolean } * */ public Boolean getKeyResult() { return keyResult; } /** * Sets the value of the keyResult property. * * @param value * allowed object is * {@link Boolean } * */ public void setKeyResult(Boolean value) { this.keyResult = value; } /** * Gets the value of the commonName property. * * @return * possible object is * {@link String } * */ public String getCommonName() { return commonName; } /** * Sets the value of the commonName property. * * @param value * allowed object is * {@link String } * */ public void setCommonName(String value) { this.commonName = value; } /** * Gets the value of the crystalSystem property. * * @return * possible object is * {@link PicklistFieldWithSmallTextRemarks } * */ public PicklistFieldWithSmallTextRemarks getCrystalSystem() { return crystalSystem; } /** * Sets the value of the crystalSystem property. * * @param value * allowed object is * {@link PicklistFieldWithSmallTextRemarks } * */ public void setCrystalSystem(PicklistFieldWithSmallTextRemarks value) { this.crystalSystem = value; } /** * Gets the value of the bravaisLattice property. * * @return * possible object is * {@link PicklistField } * */ public PicklistField getBravaisLattice() { return bravaisLattice; } /** * Sets the value of the bravaisLattice property. * * @param value * allowed object is * {@link PicklistField } * */ public void setBravaisLattice(PicklistField value) { this.bravaisLattice = value; } /** * Gets the value of the pointGroup property. * * @return * possible object is * {@link String } * */ public String getPointGroup() { return pointGroup; } /** * Sets the value of the pointGroup property. * * @param value * allowed object is * {@link String } * */ public void setPointGroup(String value) { this.pointGroup = value; } /** * Gets the value of the spaceGroup property. * * @return * possible object is * {@link String } * */ public String getSpaceGroup() { return spaceGroup; } /** * Sets the value of the spaceGroup property. * * @param value * allowed object is * {@link String } * */ public void setSpaceGroup(String value) { this.spaceGroup = value; } /** * Gets the value of the crystallographicPlanes property. * * @return * possible object is * {@link String } * */ public String getCrystallographicPlanes() { return crystallographicPlanes; } /** * Sets the value of the crystallographicPlanes property. * * @param value * allowed object is * {@link String } * */ public void setCrystallographicPlanes(String value) { this.crystallographicPlanes = value; } /** * Gets the value of the remarksOnResults property. * * @return * possible object is * {@link PicklistFieldWithMultiLineTextRemarks } * */ public PicklistFieldWithMultiLineTextRemarks getRemarksOnResults() { return remarksOnResults; } /** * Sets the value of the remarksOnResults property. * * @param value * allowed object is * {@link PicklistFieldWithMultiLineTextRemarks } * */ public void setRemarksOnResults(PicklistFieldWithMultiLineTextRemarks value) { this.remarksOnResults = value; } } } } }
lgpl-3.0
logsniffer/logsniffer
logsniffer-core/src/main/java/com/logsniffer/model/LogRawAccess.java
1964
/******************************************************************************* * logsniffer, open source tool for viewing, monitoring and analysing log data. * Copyright (c) 2015 Scaleborn UG, www.scaleborn.com * * logsniffer 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. * * logsniffer 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 com.logsniffer.model; import java.io.IOException; /** * General read access to the underlying log with an abstract pointer concept * which allows distinct positioning in a log. Whenever {@link #getPointer()} * returns a pointer with {@link LogPointer#isEOF()} no data is read anymore * even more is written in the mean time after the log instance was * instantiated. A new access instance has to be retrieved from the source to * get the new data. * * @author mbok * */ public interface LogRawAccess<STREAMTYPE extends LogInputStream> extends LogPointerFactory { /** * Returns an input stream to read from the log beginning from the pointer. * * @param from * the pointer to start the stream from; null indicates the log * start. * @return log stream * @throws IOException * in case of errors */ STREAMTYPE getInputStream(LogPointer from) throws IOException; Navigation<?> getNavigation(); }
lgpl-3.0
jason-lang/jason
src/main/java/jason/architecture/AgArch.java
8392
package jason.architecture; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import jason.asSemantics.ActionExec; import jason.asSemantics.Message; import jason.asSemantics.TransitionSystem; import jason.asSyntax.Literal; import jason.infra.local.LocalAgArch; import jason.runtime.RuntimeServices; /** * Base agent architecture class that defines the overall agent architecture; * the AS interpreter is the reasoner (a kind of mind) within this * architecture (a kind of body). * * <p> * The agent reasoning cycle (implemented in TransitionSystem class) calls these * methods to get perception, action, and communication. * * <p> * This class implements a Chain of Responsibilities design pattern. * Each member of the chain is a subclass of AgArch. The last arch in the chain is the infrastructure tier (Local, JADE, Saci, ...). * The getUserAgArch method returns the first arch in the chain. * * Users can customise the architecture by overriding some methods of this class. */ public class AgArch implements Comparable<AgArch>, Serializable { private static final long serialVersionUID = 1L; private TransitionSystem ts = null; /** * Successor in the Chain of Responsibility */ private AgArch successor = null; private AgArch firstArch = null; /** the current cycle number, in case of sync execution mode */ private int cycleNumber = 0; public AgArch() { firstArch = this; } public void init() throws Exception { } /** * A call-back method called by the infrastructure tier * when the agent is about to be killed. */ public void stop() { if (successor != null) successor.stop(); } // Management of the chain of responsibility /** Returns the first architecture in the chain of responsibility pattern */ public AgArch getFirstAgArch() { return firstArch; } public AgArch getNextAgArch() { return successor; } public List<String> getAgArchClassesChain() { List<String> all = new ArrayList<>(); AgArch a = getFirstAgArch(); while (a != null) { all.add(0,a.getClass().getName()); a = a.getNextAgArch(); } return all; } public void insertAgArch(AgArch arch) { if (arch != firstArch) // to avoid loops arch.successor = firstArch; if (ts != null) { arch.ts = this.ts; ts.setAgArch(arch); } setFirstAgArch(arch); } private void setFirstAgArch(AgArch arch) { firstArch = arch; if (successor != null) successor.setFirstAgArch(arch); } public void createCustomArchs(Collection<String> archs) throws Exception { if (archs == null) return; for (String agArchClass: archs) { // user custom arch if (!agArchClass.equals(AgArch.class.getName()) && !agArchClass.equals(LocalAgArch.class.getName())) { try { AgArch a = (AgArch) Class.forName(agArchClass).getConstructor().newInstance(); a.setTS(ts); // so a.init() can use TS insertAgArch(a); a.init(); } catch (Exception e) { System.out.println("Error creating custom agent aarchitecture."+e); e.printStackTrace(); ts.getLogger().log(Level.SEVERE,"Error creating custom agent architecture.", e); } } } } /** * A call-back method called by TS * when a new reasoning cycle is starting */ public void reasoningCycleStarting() { //QueryProfiling q = getTS().getAg().getQueryProfiling(); //if (q != null) // q.setNbReasoningCycles(getCycleNumber()); if (successor != null) successor.reasoningCycleStarting(); } /** * A call-back method called by TS * when a new reasoning cycle finished */ public void reasoningCycleFinished() { if (successor != null) successor.reasoningCycleFinished(); } public TransitionSystem getTS() { if (ts != null) return ts; if (successor != null) return successor.getTS(); return null; } public void setTS(TransitionSystem ts) { this.ts = ts; if (successor != null) successor.setTS(ts); } /** Gets the agent's perception as a list of Literals. * The returned list will be modified by Jason. */ public Collection<Literal> perceive() { if (successor == null) return null; else return successor.perceive(); } /** Reads the agent's mailbox and adds messages into the agent's circumstance */ public void checkMail() { if (successor != null) successor.checkMail(); } /** * Executes the action <i>action</i> and, when finished, adds it back in * <i>feedback</i> actions. * * @return true if the action was handled (not necessarily executed, just started) */ public void act(ActionExec action) { if (successor != null) successor.act(action); } /** called to inform that the action execution is finished */ public void actionExecuted(ActionExec act) { getTS().getC().addFeedbackAction(act); wakeUpAct(); } /** Returns true if the agent can enter in sleep mode. */ public boolean canSleep() { return (successor == null) || successor.canSleep(); } /** Puts the agent in sleep. */ /*public void sleep() { if (successor != null) successor.sleep(); }*/ public void wake() { if (successor != null) successor.wake(); } public void wakeUpSense() { if (successor != null) successor.wakeUpSense(); } public void wakeUpDeliberate() { if (successor != null) successor.wakeUpDeliberate(); } public void wakeUpAct() { if (successor != null) successor.wakeUpAct(); } /** * @deprecated use RuntimeServicesFactory.get instead */ @Deprecated public RuntimeServices getRuntimeServices() { if (successor == null) return null; else return successor.getRuntimeServices(); } /** Gets the agent's name */ public String getAgName() { if (successor == null) return "no-named"; else return successor.getAgName(); } /** Sends a Jason message */ public void sendMsg(Message m) throws Exception { if (successor != null) successor.sendMsg(m); } /** Broadcasts a Jason message */ public void broadcast(Message m) throws Exception { if (successor != null) successor.broadcast(m); } /** Checks whether the agent is running */ public boolean isRunning() { return successor == null || successor.isRunning(); } /** sets the number of the current cycle */ public void setCycleNumber(int cycle) { cycleNumber = cycle; if (successor != null) successor.setCycleNumber(cycle); } public void incCycleNumber() { setCycleNumber(cycleNumber+1); } /** gets the current cycle number */ public int getCycleNumber() { return cycleNumber; } @Override public String toString() { return "arch-"+getAgName(); } @Override public int hashCode() { return getAgName().hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof AgArch) return this.getAgName().equals( ((AgArch)obj).getAgName()); return false; } public int compareTo(AgArch o) { return getAgName().compareTo(o.getAgName()); } public Map<String,Object> getStatus() { if (successor != null) return successor.getStatus(); else return new HashMap<String, Object>(); } }
lgpl-3.0
nelt/codingmatters
codingmatters-code-analysys/src/main/java/org/codingmatters/code/analysis/model/from/code/internal/SourcePathAdder.java
2712
package org.codingmatters.code.analysis.model.from.code.internal; import net.sourceforge.pmd.dcd.graph.UsageGraphBuilder; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: nel * Date: 24/09/13 * Time: 08:38 * To change this template use File | Settings | File Templates. */ public class SourcePathAdder { public static final String PACKAGE_PATTERN = "package (.*);"; private final ArrayList<String> sourcePath = new ArrayList<>(); public SourcePathAdder(File directory) throws IOException { this.buildSourcePath(directory); } public void add(SourcePathIndexer usageGraphBuilder) throws IOException { for (String className : this.sourcePath) { usageGraphBuilder.index(className); } } private void buildSourcePath(File file) throws IOException { if(this.isJava(file)) { this.addJavaSourceFile(file); } else if(file.isDirectory()) { for (File content : file.listFiles()) { this.buildSourcePath(content); } } } private void addJavaSourceFile(File file) throws IOException { this.sourcePath.add(this.classNameFromFile(file)); } private boolean isJava(File file) { return file.getName().endsWith(".java"); } private String classNameFromFile(File file) throws IOException { String result = file.getName(); result = this.dropExtension(result); result = this.trimSeparators(result); String packageName = extractPackage(file); if(packageName != null && ! packageName.trim().equals("")) { return packageName + "." + result; } else { return result; } } private String trimSeparators(String result) { result = result.replace('\\', '.'); result = result.replace('/', '.'); return result; } private String dropExtension(String result) { return result.replaceAll("\\.java$", ""); } static public String extractPackage(File file) throws IOException { Pattern packagePattern = Pattern.compile(PACKAGE_PATTERN); Scanner fileScanner = new Scanner(file); try{ while(fileScanner.hasNextLine()) { Matcher matcher = packagePattern.matcher(fileScanner.nextLine()); if(matcher.matches()) { return matcher.group(1); } } return null; } finally { fileScanner.close(); } } }
lgpl-3.0
pvto/konte-art
src/main/java/org/konte/model/DrawingContext.java
9810
package org.konte.model; import java.awt.Color; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import org.konte.image.OutputShape; import org.konte.misc.Mathc3; import org.konte.misc.Matrix4; import org.konte.parse.ParseException; import static org.konte.misc.Mathc3.bounds1; import static org.konte.misc.Mathc3.roll1; import org.konte.misc.Matrix4Red; import org.konte.struct.RefStack; /** * * @author pvto */ public class DrawingContext implements Serializable { public Matrix4 matrix; public float R; public float G; public float B; public float A = 1f; public float layer; public short fov = 0; public Untransformable shape; public byte isDrawPhase = 0; public int d = -1; /** stores all definition-->value mappings for this instance */ public Def[] defs; public RefStack<Integer> pushstack2; // public short bitmap = -1; public short shading = -1; public float col0; public int popPushstack() { if (pushstack2 == null) return Integer.MIN_VALUE; RefStack.StackRetVal<Integer> ret = pushstack2.pop(); pushstack2 = ret.stackRef; return ret.val == null ? Integer.MIN_VALUE : ret.val; } public int peekPushstack() { if (pushstack2 == null) return Integer.MIN_VALUE; RefStack.StackRetVal<Integer> sr = pushstack2.peek(); if (sr.val == null) return Integer.MIN_VALUE; return sr.val; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeObject(matrix); out.writeFloat(R); out.writeFloat(G); out.writeFloat(B); out.writeFloat(A); out.writeFloat(layer); out.writeShort(fov); out.writeObject(shape); out.writeByte(isDrawPhase); if (isDrawPhase == 0) { out.writeInt(d); out.writeObject(defs); out.writeObject(pushstack2); // out.writeShort(bitmap); out.writeShort(shading); if (shading != -1) { out.writeFloat(col0); } } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { matrix = (Matrix4)in.readObject(); R = in.readFloat(); G = in.readFloat(); B = in.readFloat(); A = in.readFloat(); layer = in.readFloat(); fov = in.readShort(); shape = (Untransformable)in.readObject(); isDrawPhase = in.readByte(); if (isDrawPhase == 0) { d = in.readInt(); defs = (Def[])in.readObject(); pushstack2 = (RefStack<Integer>)in.readObject(); // bitmap = in.readShort(); shading = in.readShort(); if (shading != -1) { col0 = in.readFloat(); } } } public DrawingContext() { } public OutputShape toOutputShape() { OutputShape s = new OutputShape(); s.matrix = new Matrix4Red(matrix); // s.R = R; // s.G = G; // s.B = B; // s.A = A; s.col = (int)(A * 255) << 24; s.col |= (int)(R * 255) << 16; s.col |= (int)(G * 255) << 8; s.col |= (int)(B * 255); s.fov = fov; s.layer = layer; s.shape = shape; return s; } public static transient DrawingContext ZERO; static { ZERO = new DrawingContext(); ZERO.matrix = Matrix4.IDENTITY; } public static class Def implements Serializable, Comparable<Def> { public int nameid; public float defval; public Def(int nameid, float defval) { this.nameid = nameid; this.defval = defval; } public int compareTo(Def o) { return nameid - o.nameid; } public String toString() { return nameid + " " + defval; } } private static transient Def search = new Def(0,0); public float getDef(int id) { if (defs == null) return 0f; search.nameid = id; int i = Arrays.binarySearch(defs, search); return (i < 0 ? 0f : defs[i].defval); } public float getDef(int id, float defaultVal) { if (defs == null) return defaultVal; search.nameid = id; int i = Arrays.binarySearch(defs, search); return (i < 0 ? defaultVal : defs[i].defval); } public float getR() { return R; } public float getG() { return G; } public float getB() { return B; } public float getA() { return A; } public float getshading() { return (float)shading; } public float getcol0() { return col0; } public void applyShading(Model model) throws ParseException { if (shading != -1) { ColorSpace sp = model.colorSpaces.get(shading); float[] ret = sp.getValue(col0); float nega = 1f-ret[4]; R = bounds1(R*nega + ret[0]*ret[4]); G = bounds1(G*nega + ret[1]*ret[4]); B = bounds1(B*nega + ret[2]*ret[4]); A = bounds1(A*nega + ret[3]*ret[4]); shading = -1; // cleanup to decrease serialize size! } } public float getHue() { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); return tmpvals[0]; } private static transient float[] tmpvals = new float[3]; private void changeHSL() { tmpvals[1] = Mathc3.bounds1(tmpvals[1]); tmpvals[2] = Mathc3.bounds1(tmpvals[2]); int col = Color.HSBtoRGB(tmpvals[0],tmpvals[1],tmpvals[2]); R = (col >> 16 & 0xFF)/256f; G = (col >> 8 & 0xFF)/256f; B = (col & 0xFF)/256f; } public void changeHue(float delta) { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); tmpvals[0] = roll1(tmpvals[0]+delta/360); changeHSL(); } public float getL() { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); return tmpvals[2]; } public void changeLighness(float delta) { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); tmpvals[2] = bounds1(tmpvals[2]+delta); changeHSL(); } public float getSat() { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); return tmpvals[1]; } public void changeSat(float delta) { Color.RGBtoHSB((int)(R*256), (int)(G*256), (int)(B*256), tmpvals); if (tmpvals[1] > 1f) tmpvals[1] = 1f; tmpvals[1] = tmpvals[1] + delta; changeHSL(); } public Color getColor() { return new Color(R,G,B,A); } public float getlayer() { return layer; } public int getfov() { return fov; } private static final transient float PI = (float)Math.PI; private static final transient float toDeg = 180f / 3.14159265f; public float getrx() { float l = getLengthFactor(); float zt = -matrix.m21/matrix.m22; float yt = (matrix.m11)/matrix.m11; //return toDeg * ((float)Math.atan2(zt,yt)); return toDeg *( (float)Math.atan2(zt,yt)); } /* * */public float getLengthFactor() { return (float)Math.sqrt(matrix.m00*matrix.m00 + matrix.m11*matrix.m11 + matrix.m22*matrix.m22); } public float getry() { float l = getLengthFactor(); float zt = matrix.m22/matrix.m22; float xt = -matrix.m02/matrix.m00; return toDeg * ((float)Math.atan2(xt,zt) ); } public float getrz() { float l = getLengthFactor(); float xt = matrix.m00/matrix.m00; float yt = matrix.m10/matrix.m11; return toDeg * ((float)Math.atan2(yt,xt)); } public float getskewx() { throw new UnsupportedOperationException("Not yet implemented"); } public float getskewy() { throw new UnsupportedOperationException("Not yet implemented"); } public float getskewz() { throw new UnsupportedOperationException("Not yet implemented"); } public float getsx() { return matrix.m00; } public float getsy() { return matrix.m11; } public float getsz() { return matrix.m22; } public float getx() { return matrix.m03; } public float gety() { return matrix.m13; } public float getz() { return matrix.m23; } public float getMinWidth() { return Math.min(Math.abs(matrix.m00) + Math.abs(matrix.m01) + Math.abs(matrix.m02), Math.min(Math.abs(matrix.m10) + Math.abs(matrix.m11) + Math.abs(matrix.m12), Math.abs(matrix.m20) + Math.abs(matrix.m21) + Math.abs(matrix.m22))); } public float getMaxWidth() { return Math.max(Math.abs(matrix.m00) + Math.abs(matrix.m01) + Math.abs(matrix.m02), Math.max(Math.abs(matrix.m10) + Math.abs(matrix.m11) + Math.abs(matrix.m12), Math.abs(matrix.m20) + Math.abs(matrix.m21) + Math.abs(matrix.m22))); } public String toString() { StringBuilder bd = new StringBuilder(); bd.append(matrix).append("+\n"); bd.append(String.format("R %s G %s B %s A %s layer %s d %s shad %s sh-x %s", R,G,B,A,layer,d,shading,col0)); return bd.toString(); } }
lgpl-3.0
premium-minds/billy
billy-portugal/src/main/java/com/premiumminds/billy/portugal/services/export/qrcode/QRCodeStringGenerator.java
2915
/* * Copyright (C) 2017 Premium Minds. * * This file is part of billy portugal (PT Pack). * * billy portugal (PT Pack) is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * billy portugal (PT Pack) is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with billy portugal (PT Pack). If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.billy.portugal.services.export.qrcode; import com.premiumminds.billy.portugal.Config; import com.premiumminds.billy.portugal.Config.Key; import com.premiumminds.billy.portugal.services.entities.PTGenericInvoice; import com.premiumminds.billy.portugal.services.export.exceptions.RequiredFieldNotFoundException; import javax.inject.Inject; public class QRCodeStringGenerator { private final Config config; private final PTContexts ptContexts; @Inject public QRCodeStringGenerator() { this.config = new Config(); this.ptContexts= new PTContexts( this.config.getUID(Config.Key.Context.Portugal.UUID), this.config.getUID(Config.Key.Context.Portugal.Continental.UUID), this.config.getUID(Config.Key.Context.Portugal.Azores.UUID), this.config.getUID(Config.Key.Context.Portugal.Madeira.UUID) ); } public String generateQRCodeData(PTGenericInvoice document) throws RequiredFieldNotFoundException { QRCodeData qrCodeData = new QRCodeData.QRCodeDataBuilder() .withSeriesNumber(document.getSeriesNumber()) .withBusinessFinancialID(document.getBusiness().getFinancialID()) .withDocumentType(document.getType()) .withIsCancelled(document.isCancelled()) .withIsBilled(document.isBilled()) .withIsSelfBilled(document.isSelfBilled()) .withDocumentDate(document.getDate()) .withDocumentNumber(document.getNumber()) .withEntries(document.getEntries()) .withTaxAmount(document.getTaxAmount()) .withAmountWithTax(document.getAmountWithTax()) .withHash(document.getHash()) .withApplication(document.getBusiness().getApplications()) .withPTContexts(ptContexts) .withGenericCustomerUID(this.config.getUID(Key.Customer.Generic.UUID)) .withCustomer(document.getCustomer()) .withATCUD(document.getATCUD()) .build(); return QRCodeBuilder.generateQRCodeString(qrCodeData); } }
lgpl-3.0
anandswarupv/DataCleaner
desktop/ui/src/main/java/org/datacleaner/panels/equalsfilter/EqualsFilterComponentBuilderPresenterRenderer.java
2636
/** * DataCleaner (community edition) * Copyright (C) 2014 Neopost - Customer Information Management * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.datacleaner.panels.equalsfilter; import javax.inject.Inject; import org.datacleaner.api.Renderer; import org.datacleaner.api.RendererBean; import org.datacleaner.api.RendererPrecedence; import org.datacleaner.beans.filter.EqualsFilter; import org.datacleaner.beans.filter.ValidationCategory; import org.datacleaner.bootstrap.WindowContext; import org.datacleaner.guice.DCModule; import org.datacleaner.job.builder.FilterComponentBuilder; import org.datacleaner.panels.ComponentBuilderPresenterRenderingFormat; import org.datacleaner.panels.FilterComponentBuilderPresenter; import org.datacleaner.widgets.properties.PropertyWidgetFactory; /** * Specialized {@link Renderer} for a {@link FilterComponentBuilderPresenter} for * {@link EqualsFilter}. */ @RendererBean(ComponentBuilderPresenterRenderingFormat.class) public class EqualsFilterComponentBuilderPresenterRenderer implements Renderer<FilterComponentBuilder<EqualsFilter, ValidationCategory>, FilterComponentBuilderPresenter> { @Inject WindowContext windowContext; @Inject DCModule dcModule; @Override public RendererPrecedence getPrecedence(FilterComponentBuilder<EqualsFilter, ValidationCategory> fjb) { if (fjb.getDescriptor().getComponentClass() == EqualsFilter.class) { return RendererPrecedence.HIGH; } return RendererPrecedence.NOT_CAPABLE; } @Override public FilterComponentBuilderPresenter render(FilterComponentBuilder<EqualsFilter, ValidationCategory> fjb) { final PropertyWidgetFactory propertyWidgetFactory = dcModule.createChildInjectorForComponent(fjb).getInstance( PropertyWidgetFactory.class); return new EqualsFilterComponentBuilderPresenter(fjb, windowContext, propertyWidgetFactory); } }
lgpl-3.0
Robijnvogel/Galacticraft-Planets
common/micdoodle8/mods/galacticraft/mars/client/gui/GCMarsGuiTerraformer.java
5375
package micdoodle8.mods.galacticraft.mars.client.gui; import mekanism.api.EnumColor; import micdoodle8.mods.galacticraft.core.GalacticraftCore; import micdoodle8.mods.galacticraft.core.util.PacketUtil; import micdoodle8.mods.galacticraft.mars.GalacticraftMars; import micdoodle8.mods.galacticraft.mars.inventory.GCMarsContainerTerraformer; import micdoodle8.mods.galacticraft.mars.tile.GCMarsTileEntityTerraformer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; import universalelectricity.core.electricity.ElectricityDisplay; import universalelectricity.core.electricity.ElectricityDisplay.ElectricUnit; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.network.PacketDispatcher; public class GCMarsGuiTerraformer extends GuiContainer { private static final ResourceLocation terraformerGui = new ResourceLocation(GalacticraftMars.TEXTURE_DOMAIN, "textures/gui/terraformer.png"); private GCMarsTileEntityTerraformer terraformer; private GuiButton enableTreesButton; private GuiButton enableGrassButton; public GCMarsGuiTerraformer(InventoryPlayer par1InventoryPlayer, GCMarsTileEntityTerraformer terraformer) { super(new GCMarsContainerTerraformer(par1InventoryPlayer, terraformer)); this.ySize = 228; this.terraformer = terraformer; } @Override public void drawScreen(int par1, int par2, float par3) { if (this.terraformer.disableCooldown > 0) { this.enableTreesButton.enabled = false; this.enableGrassButton.enabled = false; } else { this.enableTreesButton.enabled = true; this.enableGrassButton.enabled = true; } this.enableTreesButton.displayString = (this.terraformer.treesDisabled ? "Enable" : "Disable") + " Trees"; this.enableGrassButton.displayString = (this.terraformer.grassDisabled ? "Enable" : "Disable") + " Grass"; super.drawScreen(par1, par2, par3); } @Override public void initGui() { super.initGui(); this.buttonList.clear(); final int var5 = (this.width - this.xSize) / 2; final int var6 = (this.height - this.ySize) / 2; this.enableTreesButton = new GuiButton(0, var5 + 98, var6 + 85, 72, 20, "Enable Trees"); this.enableGrassButton = new GuiButton(1, var5 + 98, var6 + 109, 72, 20, "Enable Grass"); this.buttonList.add(this.enableTreesButton); this.buttonList.add(this.enableGrassButton); } @Override protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { switch (par1GuiButton.id) { case 0: PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, 17, new Object[] { this.terraformer.xCoord, this.terraformer.yCoord, this.terraformer.zCoord, 0 })); break; case 1: PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, 17, new Object[] { this.terraformer.xCoord, this.terraformer.yCoord, this.terraformer.zCoord, 1 })); break; } } } @Override protected void drawGuiContainerForegroundLayer(int par1, int par2) { String displayString = "Terraformer"; this.fontRenderer.drawString(displayString, this.xSize / 2 - this.fontRenderer.getStringWidth(displayString) / 2, 5, 4210752); this.fontRenderer.drawString(StatCollector.translateToLocal("container.inventory"), 8, 135, 4210752); this.fontRenderer.drawSplitString(this.getStatus(), 105, 24, this.xSize - 105, 4210752); this.fontRenderer.drawString(ElectricityDisplay.getDisplay(this.terraformer.ueWattsPerTick * 20, ElectricUnit.WATT), 105, 56, 4210752); this.fontRenderer.drawString(ElectricityDisplay.getDisplay(this.terraformer.getVoltage(), ElectricUnit.VOLTAGE), 105, 68, 4210752); } private String getStatus() { if (this.terraformer.getEnergyStored() <= 0.0F) { return EnumColor.RED + "Not Enough Energy"; } if (this.terraformer.grassDisabled && this.terraformer.treesDisabled) { return EnumColor.ORANGE + "Disabled"; } if (this.terraformer.terraformBubble.getSize() < this.terraformer.terraformBubble.MAX_SIZE) { return EnumColor.YELLOW + "Bubble Expanding"; } if (this.terraformer.terraformableBlocksListSize <= 0) { return EnumColor.RED + "No Valid Blocks in Bubble"; } return EnumColor.BRIGHT_GREEN + "Terraforming"; } @Override protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.renderEngine.func_110577_a(GCMarsGuiTerraformer.terraformerGui); final int var5 = (this.width - this.xSize) / 2; final int var6 = (this.height - this.ySize) / 2; this.drawTexturedModalRect(var5, var6, 0, 0, this.xSize, this.ySize); } }
lgpl-3.0
zakski/project-soisceal
gospel-java-ex/src/main/java/alice/tuprologx/pj/engine/TheoryFilter.java
2422
package alice.tuprologx.pj.engine; import alice.tuprologx.pj.model.*; import java.util.Vector; /** * @author maurizio */ class TheoryFilter { private static final String base_filter_string = "filter(L,R):-filter(L,[],R).\n" + "filter([],X,X).\n" + "filter([H|T],F,R):-call(H),append(F,[H],Z),filter(T,Z,R).\n" + "filter([H|T],F,R):-not call(H),filter(T,F,R).\n"; private static final Theory base_filter = new Theory(base_filter_string); private final Theory _theory; private final Theory _filter; protected PJProlog _engine; /** * Creates a new instance of TheoryFilter */ private TheoryFilter(Theory theory, Theory filter) { _theory = theory; _filter = filter; } public TheoryFilter(Theory theory, String filter) { this(theory, new Theory(filter)); } @SuppressWarnings("unchecked") public Theory apply() { Var<List<Clause<?, ?>>> filtered_list = new Var<>("X"); Compound2<List<Clause<?, ?>>, Var<List<Clause<?, ?>>>> goal = new Compound2<>("filter", _theory, filtered_list); try { PJProlog p = new PJProlog(); p.setTheory(_filter); p.addTheory(base_filter); //System.out.println(p.getTheory()); //p.setTheory(p.getTheory()); //System.out.println(goal.marshal()); PrologSolution<?, ?> sol = p.solve(goal); List<Term<?>> res = sol.getTerm("X"); //System.out.println("PIPPO="+res); Vector<Clause<?, ?>> filtered_clauses = new Vector<>(); for (Term<?> t : res) { if (t instanceof Compound2 && ((Compound2<Term<?>, Term<?>>) t).getName().equals(":-")) { filtered_clauses.add(new Clause<Term<?>, Term<?>>(((Compound2<Term<?>, Term<?>>) t).get0(), ((Compound2<Term<?>, Term<?>>) t).get1())); } else { filtered_clauses.add(new Clause<Term<?>, Term<?>>(t, null)); } } return new Theory(filtered_clauses); } catch (Exception e) { e.printStackTrace(); //Var<Var<Int>> vvi = null; //Term<Var<Int>> ti3 = null; //Term<? extends Term<Int>> ti = null; //Int i = null; //ti = i; //ti = vvi; return _theory; } } }
lgpl-3.0
TehDreamTeam/SE42
logic/src/test/java/nl/tehdreamteam/se42/logic/validator/input/impl/NonNullInputValidatorTest.java
1370
package nl.tehdreamteam.se42.logic.validator.input.impl; import nl.tehdreamteam.se42.logic.exception.ServerError; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; /** * @author Oscar de Leeuw */ public class NonNullInputValidatorTest { private NonNullInputValidator validator; private ServerError error; @Before public void setUp() throws Exception { error = new ServerError("henk", 1); } @Test public void validate_withNull_returnsError() throws Exception { makeValidatorWithNullInput(); checkValidationsFails(); } @Test public void validate_withNonNull_returnsNull() throws Exception { makeValidatorWithNonNullInput(); checkValidationSucceeds(); } private void checkValidationsFails() { ServerError actual = validator.validate(); ServerError expected = error; assertSame(expected, actual); } private void checkValidationSucceeds() { ServerError actual = validator.validate(); assertNull(actual); } private void makeValidatorWithNullInput() { validator = new NonNullInputValidator(error, null); } private void makeValidatorWithNonNullInput() { validator = new NonNullInputValidator(error, ""); } }
unlicense
HenryLoenwind/EnderIO
enderio-base/src/main/java/crazypants/enderio/base/loot/AnvilCapacitorRecipe.java
4751
package crazypants.enderio.base.loot; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.apache.commons.lang3.tuple.Pair; import crazypants.enderio.base.EnderIO; import crazypants.enderio.base.Log; import crazypants.enderio.base.capacitor.CapacitorHelper; import crazypants.enderio.base.capacitor.CapacitorHelper.SetType; import crazypants.enderio.base.loot.WeightedUpgrade.WeightedUpgradeImpl; import crazypants.enderio.util.NbtValue; import crazypants.enderio.util.Prep; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.AnvilUpdateEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import static crazypants.enderio.base.init.ModObject.itemBasicCapacitor; public class AnvilCapacitorRecipe { public static void create() { MinecraftForge.EVENT_BUS.register(AnvilCapacitorRecipe.class); } @SubscribeEvent public static void handleAnvilEvent(AnvilUpdateEvent evt) { ItemStack left = evt.getLeft(); ItemStack right = evt.getRight(); if (Prep.isInvalid(left) || Prep.isInvalid(right) || left.getItem() != itemBasicCapacitor.getItem() || right.getItem() != itemBasicCapacitor.getItem() || left.getMetadata() < 3 || right.getMetadata() < 3 || left.getMetadata() != right.getMetadata() || left.getCount() > right.getCount()) { return; } List<Pair<String, Float>> dataLeft = CapacitorHelper.getCapDataRaw(left); List<Pair<String, Float>> dataRight = CapacitorHelper.getCapDataRaw(right); if (dataLeft == null || dataRight == null || dataLeft.isEmpty() || dataRight.isEmpty()) { return; } Map<WeightedUpgrade, Pair<Float, Float>> data = new HashMap<WeightedUpgrade, Pair<Float, Float>>(); float seed = 0f; for (Pair<String, Float> pair : dataLeft) { WeightedUpgrade weightedUpgrade = WeightedUpgrade.getByRawString(pair.getKey()); if (weightedUpgrade == null) { return; } data.put(weightedUpgrade, Pair.of(pair.getValue(), (Float) null)); seed += pair.getValue(); } for (Pair<String, Float> pair : dataRight) { WeightedUpgrade weightedUpgrade = WeightedUpgrade.getByRawString(pair.getKey()); if (weightedUpgrade == null) { return; } if (data.containsKey(weightedUpgrade)) { data.put(weightedUpgrade, Pair.of(pair.getValue(), data.get(weightedUpgrade).getKey())); } else { data.put(weightedUpgrade, Pair.of(pair.getValue(), (Float) null)); } seed += pair.getValue(); } Random rand = new Random((long) (seed * 1000)); Map<WeightedUpgrade, Float> result = new HashMap<WeightedUpgrade, Float>(); for (WeightedUpgradeImpl wai : WeightedUpgrade.getWeightedupgrades()) { WeightedUpgrade wa = wai.getUpgrade(); if (data.containsKey(wa)) { final float combine = combine(rand, data.get(wa)); result.put(wa, combine); Log.debug("Combining " + wa + " " + data.get(wa).getKey() + " and " + data.get(wa).getValue() + " to " + combine); } } float baselevel = Math.max(CapacitorHelper.getCapLevelRaw(left), CapacitorHelper.getCapLevelRaw(right)); if (baselevel < 5 && rand.nextFloat() < .5f) { baselevel++; } ItemStack stack = left.copy(); String name = LootSelector.buildBaseName(EnderIO.lang.localize("loot.capacitor.name"), baselevel); stack = CapacitorHelper.addCapData(stack, SetType.LEVEL, null, baselevel); for (Entry<WeightedUpgrade, Float> entry : result.entrySet()) { stack = CapacitorHelper.addCapData(stack, entry.getKey().setType, entry.getKey().capacitorKey, entry.getValue()); name = LootSelector.buildName(EnderIO.lang.localize(entry.getKey().langKey, name), entry.getValue()); } NbtValue.CAPNAME.setString(stack, name); evt.setOutput(stack); evt.setMaterialCost(stack.getCount()); evt.setCost((int) (baselevel * baselevel) * stack.getCount()); } static private float combine(Random rand, Pair<Float, Float> pair) { if (pair.getRight() == null) { return pair.getLeft(); } return combine(rand, pair.getLeft(), pair.getRight()); } static private float combine(Random rand, float a, float b) { float min = a < b ? a : b; float center = a < b ? b : a; float offsetLow = Math.max(center - min, 0.1f); float max = Math.min(center + offsetLow, 4.75f); float offsetHigh = max - center; float gaussian = (float) rand.nextGaussian(); if (gaussian <= 0) { return Math.max(min, center + gaussian * offsetLow); } else { return Math.min(max, center + gaussian * offsetHigh); } } }
unlicense
Grupp2/GameBoard-API-Games
testsrc/othello/backend/classhelpers/GamePieceHelperTest.java
5985
package othello.backend.classhelpers; import othello.backend.State; import othello.backend.classhelpers.GamePieceHelper; import othello.backend.classhelpers.PlayerHelper; import game.impl.Board; import game.impl.BoardLocation; import game.impl.GamePiece; import game.impl.Player; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class GamePieceHelperTest { @Before public void setUp() throws Exception { } @Test public void testGetOwnerOfPiece() throws Exception { State state = mock(State.class); PlayerHelper playerHelper = mock(PlayerHelper.class); GamePieceHelper pieceHelper = new GamePieceHelper(state, playerHelper); Player player1 = mock(Player.class); Player player2 = mock(Player.class); GamePiece piece = mock(GamePiece.class); when(player1.hasPiece(piece)).thenReturn(true).thenReturn(false); when(playerHelper.getPlayerOne()).thenReturn(player1); when(playerHelper.getPlayerTwo()).thenReturn(player2); assertEquals(player1, pieceHelper.getOwnerOfPiece(piece)); assertEquals(player2, pieceHelper.getOwnerOfPiece(piece)); } @Test public void testChangeOwnerOfPiece() throws Exception { State state = mock(State.class); PlayerHelper playerHelper = mock(PlayerHelper.class); final GamePiece thePiece = mock(GamePiece.class); final BoardLocation locationOfPiece = new BoardLocation("test location"); final Player currentOwner = mock(Player.class); final Player newOwner = mock(Player.class); locationOfPiece.setPiece(thePiece); List<GamePiece> currentOwnerPieces = new ArrayList<GamePiece>(){{ add(thePiece); }}; List<GamePiece> newOwnerPieces = new ArrayList<GamePiece>(); GamePieceHelper pieceHelper = new GamePieceHelper(state, playerHelper){ public Player getOwnerOfPiece(GamePiece piece){ return currentOwner; } public BoardLocation getLocationOfPiece(GamePiece piece){ return locationOfPiece; } }; when(currentOwner.getPieces()).thenReturn(currentOwnerPieces); when(newOwner.getPieces()).thenReturn(newOwnerPieces); when(playerHelper.getPlayerOne()).thenReturn(currentOwner).thenReturn(currentOwner); when(playerHelper.getPlayerTwo()).thenReturn(newOwner); pieceHelper.changeOwnerOfPiece(thePiece); assertEquals(0, currentOwnerPieces.size()); assertEquals(1, newOwnerPieces.size()); assertNotEquals(thePiece, locationOfPiece.getPiece()); assertTrue(locationOfPiece.getPiece() instanceof GamePiece); } @Test public void testGetLocationOfPiece() throws Exception { State state = mock(State.class); PlayerHelper playerHelper = mock(PlayerHelper.class); GamePieceHelper pieceHelper = new GamePieceHelper(state, playerHelper); GamePiece piece = mock(GamePiece.class); Board board = mock(Board.class); when(state.getBoard()).thenReturn(board); BoardLocation location = mock(BoardLocation.class); when(location.getPiece()).thenReturn(piece).thenReturn(piece); when(board.getLocations()) .thenReturn(makeLocationMock1(location)) .thenReturn(makeLocationMock2(location)) .thenReturn(makeLocationMock3()); assertEquals(location, pieceHelper.getLocationOfPiece(piece)); assertEquals(location, pieceHelper.getLocationOfPiece(piece)); assertEquals("Null location", pieceHelper.getLocationOfPiece(piece).getId()); } public List<BoardLocation> makeLocationMock1(final BoardLocation locationMock){ return new ArrayList<BoardLocation>(){{ BoardLocation location1 = mock(BoardLocation.class); BoardLocation location2 = mock(BoardLocation.class); BoardLocation location3 = mock(BoardLocation.class); BoardLocation location4 = mock(BoardLocation.class); BoardLocation location5 = mock(BoardLocation.class); BoardLocation location6 = mock(BoardLocation.class); add(locationMock); add(location1); add(location2); add(location3); add(location4); add(location5); add(location6); }}; } public List<BoardLocation> makeLocationMock2(final BoardLocation locationMock){ return new ArrayList<BoardLocation>(){{ BoardLocation location1 = mock(BoardLocation.class); BoardLocation location2 = mock(BoardLocation.class); BoardLocation location3 = mock(BoardLocation.class); BoardLocation location4 = mock(BoardLocation.class); BoardLocation location5 = mock(BoardLocation.class); BoardLocation location6 = mock(BoardLocation.class); add(location1); add(location2); add(location3); add(location4); add(location5); add(location6); add(locationMock); }}; } public List<BoardLocation> makeLocationMock3(){ return new ArrayList<BoardLocation>(){{ BoardLocation location1 = mock(BoardLocation.class); BoardLocation location2 = mock(BoardLocation.class); BoardLocation location3 = mock(BoardLocation.class); BoardLocation location4 = mock(BoardLocation.class); BoardLocation location5 = mock(BoardLocation.class); BoardLocation location6 = mock(BoardLocation.class); add(location1); add(location2); add(location3); add(location4); add(location5); add(location6); }}; } }
unlicense
luisfsantos/PO-Projecto
aulaPratica3/arabiannights/FriendlyGenie.java
667
package arabiannights; /** *Classe que implementa o FriendlyGenie que e' libertado quando a *lampada esta' contente. *@see Genie. */ public class FriendlyGenie extends Genie { /** *Construtor de FriendlyGenie. *@param Recebe o nu'mero de desejos que o Genie podera' conceber. */ public FriendlyGenie(int wishes){ super(wishes); } /** *Interface do FriendlyGenie que indica quantos desejos realizou *e quantos ainda pode realizar. *@return String a indicar desejos realizados e disponi'veis. */ public String toString(){ return "Friendly genie has granted" + getGrantedWishes() + " wishes and still has" + getRemainingWishes() + " to grant."; } }
unlicense
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/dialog/requestdialog/NewThreadRequestDialogFragment.java
2573
package me.ykrank.s1next.view.dialog.requestdialog; import android.os.Bundle; import io.reactivex.Single; import me.ykrank.s1next.BuildConfig; import me.ykrank.s1next.R; import me.ykrank.s1next.data.api.model.Result; import me.ykrank.s1next.data.api.model.wrapper.AccountResultWrapper; /** * A dialog requests to reply to post. */ public final class NewThreadRequestDialogFragment extends BaseRequestDialogFragment<AccountResultWrapper> { public static final String TAG = NewThreadRequestDialogFragment.class.getName(); private static final String ARG_FORUM_ID = "forum_id"; private static final String ARG_TYPE_ID = "type_id"; private static final String ARG_TITLE = "title"; private static final String ARG_MESSAGE = "message"; private static final String ARG_CACHE_KEY = "cache_key"; private static final String STATUS_NEW_THREAD_SUCCESS = "post_newthread_succeed"; public static NewThreadRequestDialogFragment newInstance(int forumId, String typeId, String title, String message, String cacheKey) { NewThreadRequestDialogFragment fragment = new NewThreadRequestDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt(ARG_FORUM_ID, forumId); bundle.putString(ARG_TYPE_ID, typeId); bundle.putString(ARG_TITLE, title); bundle.putString(ARG_MESSAGE, message); bundle.putString(ARG_CACHE_KEY, cacheKey); fragment.setArguments(bundle); return fragment; } @Override protected CharSequence getProgressMessage() { return getText(R.string.dialog_progress_message_reply); } @Override protected Single<AccountResultWrapper> getSourceObservable() { Bundle bundle = getArguments(); int forumId = bundle.getInt(ARG_FORUM_ID); String title = bundle.getString(ARG_TITLE); String typeId = bundle.getString(ARG_TYPE_ID); String message = bundle.getString(ARG_MESSAGE); Integer saveAsDraft = BuildConfig.DEBUG ? 1 : null; return flatMappedWithAuthenticityToken(token -> mS1Service.newThread(forumId, token, System.currentTimeMillis(), typeId, title, message, 1, 1, saveAsDraft)); } @Override protected void onNext(AccountResultWrapper data) { Result result = data.getResult(); if (result.getStatus().equals(STATUS_NEW_THREAD_SUCCESS)) { onRequestSuccess(result.getMessage()); } else { onRequestError(result.getMessage()); } } }
unlicense
vycius/NMAkademija
app/src/main/java/com/nmakademija/nmaakademija/MainActivity.java
4977
package com.nmakademija.nmaakademija; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import com.facebook.login.LoginManager; import com.google.firebase.auth.FirebaseUser; import com.nmakademija.nmaakademija.adapter.BottomNavigationFragmentPagerAdapter; import com.nmakademija.nmaakademija.utils.NMAPreferences; import it.sephiroth.android.library.bottomnavigation.BottomNavigation; public class MainActivity extends BaseActivity implements BottomNavigation.OnMenuItemSelectionListener { public static final String EXTRA_SELECTED_TAB_INDEX = "selected_index"; private int selectedIndex; private BottomNavigation bottomNavigation; private ViewPager viewPager; @Override public boolean onCreateOptionsMenu(Menu menu) { FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser != null && currentUser.isAnonymous()) { getMenuInflater().inflate(R.menu.anonymous_main_menu, menu); } else { getMenuInflater().inflate(R.menu.main_menu, menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem account = menu.findItem(R.id.account); if (account != null && !NMAPreferences.getIsAcademic(this)) { account.setVisible(false); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.account: Intent intent = new Intent(this, EditProfileActivity.class); startActivity(intent); return true; case R.id.logout: case R.id.login: openLogin(); return true; } return super.onOptionsItemSelected(item); } public void openLogin() { FirebaseUser user = mAuth.getCurrentUser(); if (user != null && user.isAnonymous()) { user.delete(); } NMAPreferences.clear(this); mAuth.signOut(); LoginManager.getInstance().logOut(); startActivity(new Intent(this, StartActivity.class)); finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setHomeButtonEnabled(false); setContentView(R.layout.activity_main); if (savedInstanceState != null) { selectedIndex = savedInstanceState.getInt(EXTRA_SELECTED_TAB_INDEX); } bottomNavigation = (BottomNavigation) findViewById(R.id.bottom_navigation); viewPager = (ViewPager) findViewById(R.id.view_pager); initBottomNavigation(); } void initBottomNavigation() { viewPager.setAdapter(new BottomNavigationFragmentPagerAdapter(getSupportFragmentManager())); viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(final int position) { bottomNavigation.setSelectedIndex(position, false); } }); bottomNavigation.setSelectedIndex(selectedIndex, false); setCurrentFragmentProperties(selectedIndex); bottomNavigation.setOnMenuItemClickListener(this); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(EXTRA_SELECTED_TAB_INDEX, selectedIndex); super.onSaveInstanceState(outState); } void setCurrentFragmentProperties(int position) { selectedIndex = position; int subtitle; switch (position) { case 0: subtitle = R.string.news; break; case 1: subtitle = R.string.schedule; break; case 2: subtitle = R.string.academics; break; case 3: subtitle = R.string.settings; break; default: throw new IllegalArgumentException("Tab with index " + position + " does not exists"); } ActionBar bar = getSupportActionBar(); if (bar != null) { bar.setSubtitle(getResources().getString(subtitle)); } } @Override protected void onDestroy() { viewPager.clearOnPageChangeListeners(); super.onDestroy(); } @Override public void onMenuItemSelect(@IdRes int itemId, final int position, boolean fromUser) { setCurrentFragmentProperties(position); if (fromUser) { viewPager.setCurrentItem(position); } } @Override public void onMenuItemReselect(@IdRes int itemId, final int position, boolean fromUser) { } }
unlicense
ExcitedName/ExQuickMod
src/main/java/com/excitedname/exq/ingredients/ground/GroundCharcoal.java
754
package com.excitedname.exq.ingredients.ground; import com.excitedname.exq.creativetabs.Tabs; import com.excitedname.exq.ref.Ref; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; public class GroundCharcoal extends Item { public GroundCharcoal(){ this.setUnlocalizedName("Ground Charcoal"); this.setTextureName("Ground Charcoal"); this.setCreativeTab(Tabs.IngTab); } //Texture Icon @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconReg){ itemIcon = iconReg.registerIcon(Ref.MOD_ID + ":" + this.getUnlocalizedName() .substring(this.getUnlocalizedName().indexOf(".")+1)); } }
unlicense
dkandalov/katas
java/src/main/java/katas/java/sort/insertsort/InsertSort7.java
1403
package katas.java.sort.insertsort; import org.junit.Test; import katas.java.permutation.Perm0; import static org.junit.Assert.*; import static java.util.Arrays.*; import java.util.Arrays; import java.util.List; /** * @author DKandalov */ public class InsertSort7 { private static List<Integer> emptyList = Arrays.<Integer>asList(); @Test public void shouldSortList() { assertEquals(sort(emptyList), emptyList); assertEquals(sort(asList(1)), asList(1)); assertEquals(sort(asList(1, 2)), asList(1, 2)); assertEquals(sort(asList(1, 2, 3)), asList(1, 2, 3)); assertEquals(sort(asList(3, 1, 2)), asList(1, 2, 3)); for (List<Integer> list : Perm0.perm(asList(1, 2, 3, 4, 5))) { assertEquals(sort(list), asList(1, 2, 3, 4, 5)); } } public List<Integer> sort(List<Integer> list) { if (list.size() < 2) return list; for (int i = 1; i < list.size(); i++) { for (int j = i; j >= 1; j--) { if (!compareAndExchange(list, j - 1, j)) break; } } return list; } private static boolean compareAndExchange(List<Integer> list, int pos1, int pos2) { if (list.get(pos1) <= list.get(pos2)) return false; int tmp = list.get(pos1); list.set(pos1, list.get(pos2)); list.set(pos2, tmp); return true; } }
unlicense
dashjim/myCar
myCar/src/test/AllTests.java
552
/* * ´´½¨ÈÕÆÚ 2009-3-27 * * TODO Òª¸ü¸Ä´ËÉú³ÉµÄÎļþµÄÄ£°å£¬ÇëתÖÁ * ´°¿Ú £­ Ê×Ñ¡Ïî £­ Java £­ ´úÂëÑùʽ £­ ´úÂëÄ£°å */ package test; import test.dao.UserDaoTest; import test.service.UserServiceTest; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { Class[] testClasses = { UserServiceTest.class, UserDaoTest.class }; TestSuite suite= new TestSuite(testClasses); // TestSuite suite= new TestSuite(); // suite.addTest(new UserServiceTest()); return suite; } }
unlicense
ghzmdr/EventTracker
app/src/main/java/com/ghzmdr/eventtracker/EventHolder.java
453
package com.ghzmdr.eventtracker; import com.google.android.gms.maps.model.Marker; import java.util.HashMap; /** * Created by ghzmdr on 13/01/15. */ public class EventHolder { private static EventHolder ref; public static Event event; public static HashMap<Marker, Event> markerEventMap; public static EventHolder getReference(){ if (ref == null){ ref = new EventHolder(); } return ref; } }
unlicense
hhhayssh/nflpicks
src/main/java/nflpicks/model/Division.java
6060
package nflpicks.model; import java.util.List; /** * * Represents the division that a team is in. Each division * is in a conference. * * @author albundy * */ public class Division { /** * The division's id. */ protected int id; /** * The conference the division is in. */ protected int conferenceId; /** * The name of the division. */ protected String name; /** * The teams in the division. */ protected List<Team> teams; /** * The year the division started. */ protected String startYear; /** * If the division was changed, this is the year it ended. */ protected String endYear; /** * If the division has ended, this is the name of the active division it's * linked to. */ protected String currentName; public Division(){ } /** * * A convenience constructor for making a division without using all the setters. * * @param id * @param conferenceId * @param name * @param teams * @param startYear * @param endYear * @param currentName */ public Division(int id, int conferenceId, String name, List<Team> teams, String startYear, String endYear, String currentName){ this.id = id; this.conferenceId = conferenceId; this.name = name; this.teams = teams; this.startYear = startYear; this.endYear = endYear; this.currentName = currentName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getConferenceId() { return conferenceId; } public void setConferenceId(int conferenceId) { this.conferenceId = conferenceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Team> getTeams(){ return teams; } public void setTeams(List<Team> teams){ this.teams = teams; } public String getStartYear() { return startYear; } public void setStartYear(String startYear) { this.startYear = startYear; } public String getEndYear() { return endYear; } public void setEndYear(String endYear) { this.endYear = endYear; } public String getCurrentName() { return currentName; } public void setCurrentName(String currentName) { this.currentName = currentName; } /** * * A convenience function for figuring out whether this division is active or not * without having to do "endYear != null". * * @return */ public boolean isActive(){ if (endYear != null){ return false; } return true; } /** * * The hash code should turn this object into a relatively unique number * so that it can be identified by that number easily and so (hopefully) * there aren't that many "collisions" with other objects. * * It starts at a prime number repeatedly multiplies and adds the hash codes * of the variables of the objects in this class. I don't have that great of a handle * on why it's done this way (check the internet if you care) but I know * what it's trying to do. * */ @Override public int hashCode(){ int primeNumber = 31; int result = 1; result = primeNumber * result + Integer.valueOf(id).hashCode(); result = primeNumber * result + Integer.valueOf(conferenceId).hashCode(); result = primeNumber * result + (name == null ? 0 : name.hashCode()); result = primeNumber * result + (teams == null ? 0 : teams.hashCode()); result = primeNumber * result + (startYear == null ? 0 : startYear.hashCode()); result = primeNumber * result + (endYear == null ? 0 : endYear.hashCode()); result = primeNumber * result + (currentName == null ? 0 : currentName.hashCode()); return result; } /** * * Returns true if the given object has all the same values for all * the variables in this object. * */ @Override public boolean equals(Object object){ //Steps to do: // 1. If the given object is this object, it's equal. // 2. If it's null or isn't an instance of this class, it's not equal. // 3. Otherwise, just go down through each variable and return // false if it's not equal. // 4. If we get to the end, then all the variables "weren't not equal" // so that means the object is equal to this one. if (object == this){ return true; } if (object == null || !(object instanceof Division)){ return false; } Division otherDivision = (Division)object; int otherId = otherDivision.getId(); if (id != otherId){ return false; } int otherConferenceId = otherDivision.getConferenceId(); if (conferenceId != otherConferenceId){ return false; } String otherName = otherDivision.getName(); if (name != null){ if (!name.equals(otherName)){ return false; } } else { if (otherName != null){ return false; } } List<Team> otherTeams = otherDivision.getTeams(); if (teams != null){ if (!teams.equals(otherTeams)){ return false; } } else { if (otherTeams != null){ return false; } } String otherStartYear = otherDivision.getStartYear(); if (startYear != null){ if (!startYear.equals(otherStartYear)){ return false; } } else { if (otherStartYear != null){ return false; } } String otherEndYear = otherDivision.getEndYear(); if (endYear != null){ if (!endYear.equals(otherEndYear)){ return false; } } else { if (otherEndYear != null){ return false; } } String otherCurrentName = otherDivision.getCurrentName(); if (currentName != null){ if (!currentName.equals(otherCurrentName)){ return false; } } else { if (otherCurrentName != null){ return false; } } return true; } /** * * Returns the string version of this object. * */ @Override public String toString(){ String thisObjectAsAString = "id = " + id + ", conferenceId = " + conferenceId + ", name = " + name + ", teams = " + teams + ", startYear = " + startYear + ", endYear = " + endYear; return thisObjectAsAString; } }
unlicense
ddvoron/webstore
web/src/main/java/controller/CommandModifyGoods.java
5300
package controller; import com.voronovich.entity.AdditionalInfoEntity; import com.voronovich.entity.BasketEntity; import com.voronovich.entity.MainInfoEntity; import com.voronovich.entity.UsersEntity; import com.voronovich.service.Service; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Class implements the content and functionality of the page modify goods * * @author Dmitry V * @version 1.0 */ public class CommandModifyGoods implements ActionCommand { @Override public String execute(HttpServletRequest request) { String page = Action.MODIFYGOODS.inPage; Service service = Service.getService(); UsersEntity usersEntity = (UsersEntity) request.getSession(true).getAttribute("user"); if (FormHelper.isPost(request)) { int id = Integer.parseInt(request.getParameter("ID")); if (id > 0) { MainInfoEntity mainInfoEntityUpdate = service.getMainInfoService().get(id); String brand = request.getParameter("Brand"); String model = request.getParameter("Model"); Double price = Double.parseDouble(request.getParameter("Price")); String release = request.getParameter("ReleaseDate"); String picture = request.getParameter("Picture"); int fk = Integer.parseInt(request.getParameter("Department")); mainInfoEntityUpdate.setId(id); mainInfoEntityUpdate.setBrand(brand); mainInfoEntityUpdate.setModel(model); mainInfoEntityUpdate.setPrice(price); mainInfoEntityUpdate.setReleaseDate(release); mainInfoEntityUpdate.setImg(picture); mainInfoEntityUpdate.setFk_Catalog(fk); if (service.getMainInfoService().update(mainInfoEntityUpdate)) { request.setAttribute(Action.msgMessage, "Товар успешно обновлен"); page = Action.MODIFYGOODS.okPage; } else { request.setAttribute(Action.msgMessage, "Товар не обновлен"); page = Action.MODIFYGOODS.inPage; } } if (id == 0) { MainInfoEntity mainInfoEntity = new MainInfoEntity(); String brand = request.getParameter("Brand"); String model = request.getParameter("Model"); Double price = Double.parseDouble(request.getParameter("Price")); String release = request.getParameter("ReleaseDate"); String picture = request.getParameter("Picture"); int fk = Integer.parseInt(request.getParameter("Department")); mainInfoEntity.setId(id); mainInfoEntity.setBrand(brand); mainInfoEntity.setModel(model); mainInfoEntity.setPrice(price); mainInfoEntity.setReleaseDate(release); mainInfoEntity.setImg(picture); mainInfoEntity.setFk_Catalog(fk); if (service.getMainInfoService().create(mainInfoEntity)) { request.setAttribute(Action.msgMessage, "Товар успешно добавлен"); page = Action.MODIFYGOODS.okPage; } else { request.setAttribute(Action.msgMessage, "Товар не добавлен"); page = Action.MODIFYGOODS.inPage; } } if (id < 0) { id = (-1) * id; List<BasketEntity> basketEntityList = service.getBasketService().get(); for (BasketEntity basketEntity : basketEntityList) { if (basketEntity.getFk_MainInfo() == id) { service.getBasketService().delete(basketEntity); } } List<AdditionalInfoEntity> additionalInfoEntityList = service.getAdditionalInfoService().get(); for (AdditionalInfoEntity additionalInfoEntity : additionalInfoEntityList) { if (additionalInfoEntity.getFk_MainInfo() == id) { service.getAdditionalInfoService().delete(additionalInfoEntity); } } MainInfoEntity mainInfoEntityDelete = service.getMainInfoService().get(id); if (service.getMainInfoService().delete(mainInfoEntityDelete)) { request.setAttribute(Action.msgMessage, "Товар успешно удален"); page = Action.MODIFYGOODS.okPage; } else { request.setAttribute(Action.msgMessage, "Товар не удален"); page = Action.MODIFYGOODS.inPage; } } } if (usersEntity != null && usersEntity.getFk_Role() == 2) { List<MainInfoEntity> list = service.getMainInfoService().get(); request.setAttribute("list", list); } else { request.setAttribute(Action.msgMessage, "Вы не авторизированы либо не обладаете правами администратора"); } return page; } }
unlicense
ndgo/java-group-validation-example
src/test/java/TestCarValidation.java
2953
import car.Car; import car.CarModel; import interfaces.OldCarCheck; import interfaces.OneYearOldCarCheck; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import utils.Validator; import javax.validation.groups.Default; import java.util.ArrayList; import java.util.List; public class TestCarValidation { public static final String DEFAULT_OWNER = "OWNER-1"; public static final long CAR_PRICE = 1; public static final long ONE_YEAR = 1; public static final long TWENTY_FIVE_YEARS = 25; private Validator validator; @Before public void initValidator() { validator = new Validator(); } public Car getDefaultCar() { Car car = new Car(); car.setPrice(CAR_PRICE); car.setCarModel(CarModel.BENTLEY); List<String> owners = new ArrayList<String>(); owners.add(DEFAULT_OWNER); car.setOwners(owners); return car; } @Test public void testUsualValidation() { Car car = getDefaultCar(); Assert.assertEquals("[]", validator.validate(car)); } @Test public void testOldCarAge() { Car car = getDefaultCar(); car.setAge(TWENTY_FIVE_YEARS); Assert.assertEquals("[]", validator.validate(car, OldCarCheck.class)); // машине 25 лет, но не 1 год Assert.assertNotEquals("[]", validator.validate(car, OneYearOldCarCheck.class)); } @Test public void testOneYearOldCar() { Car car = getDefaultCar(); car.setAge(ONE_YEAR); Assert.assertEquals("[]", validator.validate(car, OneYearOldCarCheck.class)); } @Test public void testOneYearOldCarAndNonGroupedConstraints() { Car car = getDefaultCar(); car.setAge(ONE_YEAR); // проверить поля с аннотациями, относящиеся к группе по умолчанию, а так же поля, с аннотацииями, // относящиеся к группе OneYearOldCarCheck Assert.assertEquals("[]", validator.validate(car, Default.class, OneYearOldCarCheck.class)); car.setPrice(null); car.setOwners(null); // согласно аннотоации @NotNull проверки Car.owners и Car.price должны приводить к ошибке, // но так как не указана группа по умолчанию, а указана ТОЛЬКО группа OneYearOldCarCheck, // то проверяются ограничения, относящиеся только к группе OneYearOldCarCheck Assert.assertEquals("[]", validator.validate(car, OneYearOldCarCheck.class)); // Car.owners не должен быть null и должен содержать как минимум 1 элемент Assert.assertNotEquals("[]", validator.validate(car, Default.class, OneYearOldCarCheck.class)); } }
unlicense
SleepyTrousers/EnderIO
enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/liquid/NetworkTank.java
2036
package crazypants.enderio.conduits.conduit.liquid; import javax.annotation.Nonnull; import com.enderio.core.common.fluid.IFluidWrapper; import com.enderio.core.common.util.DyeColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; public class NetworkTank { final @Nonnull EnderLiquidConduit con; final @Nonnull EnumFacing conDir; final IFluidWrapper externalTank; final @Nonnull BlockPos conduitLoc; final boolean acceptsOuput; final @Nonnull DyeColor inputColor; final @Nonnull DyeColor outputColor; final int priority; final boolean roundRobin; final boolean selfFeed; final boolean supportsMultipleTanks; public NetworkTank(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) { this.con = con; this.conDir = conDir; conduitLoc = con.getBundle().getLocation(); externalTank = con.getExternalHandler(conDir); acceptsOuput = con.getConnectionMode(conDir).acceptsOutput(); inputColor = con.getOutputColor(conDir); outputColor = con.getInputColor(conDir); priority = con.getOutputPriority(conDir); roundRobin = con.isRoundRobinEnabled(conDir); selfFeed = con.isSelfFeedEnabled(conDir); supportsMultipleTanks = (externalTank != null) && externalTank.getTankInfoWrappers().size() > 1; } public boolean isValid() { return externalTank != null && con.getConnectionMode(conDir).isActive(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + conDir.hashCode(); result = prime * result + conduitLoc.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NetworkTank other = (NetworkTank) obj; if (conDir != other.conDir) { return false; } if (!conduitLoc.equals(other.conduitLoc)) { return false; } return true; } }
unlicense
slavni96/misc
brainFuckInterpreter/BrainInterpreter.java
2361
import java.io.IOException; public class BrainInterpreter { private static class engine{ public static void check(char[] input){ for (int i=0; i < input.length;i++) { if ((input[i] == '<') || (input[i] == '>') || (input[i] == '+') || (input[i] == '-') || (input[i] == '.') || (input[i] == ',') || (input[i] == '[') || (input[i] == ']')){ //System.out.print(turing[i] + " "); break;} else{ System.out.println("Data not allowed"); System.exit(1);} } } public static int[] calculate(char[] input){ int[] turing = new int[1000]; int pos = 0; for (int i=0;i<input.length;i++) { switch (input[i]){ case '<': if (pos == 0) pos = 1000; else pos = pos -1; break; case '>': pos = pos+1; break; case '+': turing[pos] = turing[pos]+1; break; case '-': turing[pos] = turing[pos]-1; break; case '.': System.out.println((char) turing[pos]); break; case ',': try{ char tmp = (char )System.in.read(); turing[pos] = (int) tmp; } catch (IOException io) { System.out.println("Fuck you. You don't have insert the char"); } break; case '[': break; case ']': break; } } System.out.println(pos); return turing; } public engine(String args){ char[] input = args.toCharArray(); check(input); calculate(input); //for (int i=0; i==args.length;i++){System.out.println(args[i]);} } } public static void main(String[] args){ try { engine e = new engine(args[0]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Check the input"); } } }
unlicense
dk00/old-stuff
csie/jpeg/sample.java
69048
// Version 1.0a // Copyright (C) 1998, James R. Weeks an¢ì BioElectroMech. // Visit BioElectroMech at www.obrador.com. Email James@obrador.com. // See license.txt (included below - search for LICENSE.TXT) for details // about the allowed used of this software. // This software is based in part on the work of the Independent JPEG Group. // See IJGreadme.txt (included below - search for IJGREADME.TXT) // for details about the Independent JPEG Group's license. // This encoder is inspired by the Java Jpeg encoder by Florian Raemy, // studwww.eurecom.fr/~raemy. // It borrows a great deal of code an¢ì structure from the Independent // Jpeg Group's Jpeg 6a library, Copyright Thomas G. Lane. // See license.txt for details. package net.sourceforge.processdash.ui.lib; //import java.applet.Applet; import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.*; /* * JpegEncoder - The JPEG main program which performs a jpeg compression of * an image. */ public class JpegEncoder extends Frame { //Thread runner; BufferedOutputStream outStream; //Image image; JpegInfo JpegObj; Huffman Huf; DCT dct; int imageHeight, imageWidth; int Quality; //int code; public static int[] jpegNaturalOrder = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; public JpegEncoder(Image image, int quality, OutputStream out) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(image, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { // Got to do something? } /* * Quality of the image. * 0 to 100 an¢ì from bad image quality, high compression to good * image quality low compression */ Quality=quality; /* * Getting picture information * It takes the Width, Height an¢ì RGB scans of the image. */ JpegObj = new JpegInfo(image); imageHeight=JpegObj.imageHeight; imageWidth=JpegObj.imageWidth; outStream = new BufferedOutputStream(out); dct = new DCT(Quality); Huf=new Huffman(imageWidth,imageHeight); } public void setQuality(int quality) { dct = new DCT(quality); } public int getQuality() { return Quality; } public void Compress() { WriteHeaders(outStream); WriteCompressedData(outStream); WriteEOI(outStream); try { outStream.flush(); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } public void WriteCompressedData(BufferedOutputStream outStream) { int offset, i, j, r, c,a ,b, temp = 0; int comp, xpos, ypos, xblockoffset, yblockoffset; float inputArray[][]; float dctArray1[][] = new float[8][8]; double dctArray2[][] = new double[8][8]; int dctArray3[] = new int[8*8]; /* * This method controls the compression of the image. * Starting at the upper left of the image, it compresses 8x8 blocks * of data until the entire image has been compressed. */ int lastDCvalue[] = new int[JpegObj.NumberOfComponents]; int zeroArray[] = new int[64]; // initialized to hold all zeros int Width = 0, Height = 0; int nothing = 0, not; int MinBlockWidth, MinBlockHeight; // This initial setting of MinBlockWidth an¢ì MinBlockHeight is done to // ensure they start with values larger than will actually be the case. MinBlockWidth = ((imageWidth%8 != 0) ? (int) (Math.floor((double) imageWidth/8.0) + 1)*8 : imageWidth); MinBlockHeight = ((imageHeight%8 != 0) ? (int) (Math.floor((double) imageHeight/8.0) + 1)*8: imageHeight); for (comp = 0; comp < JpegObj.NumberOfComponents; comp++) { MinBlockWidth = Math.min(MinBlockWidth, JpegObj.BlockWidth[comp]); MinBlockHeight = Math.min(MinBlockHeight, JpegObj.BlockHeight[comp]); } xpos = 0; for (r = 0; r < MinBlockHeight; r++) { for (c = 0; c < MinBlockWidth; c++) { xpos = c*8; ypos = r*8; for (comp = 0; comp < JpegObj.NumberOfComponents; comp++) { Width = JpegObj.BlockWidth[comp]; Height = JpegObj.BlockHeight[comp]; inputArray = (float[][]) JpegObj.Components[comp]; for(i = 0; i < JpegObj.VsampFactor[comp]; i++) { for(j = 0; j < JpegObj.HsampFactor[comp]; j++) { xblockoffset = j * 8; yblockoffset = i * 8; for (a = 0; a < 8; a++) { for (b = 0; b < 8; b++) { // I believe this is where the dirty line at the bottom of the image is // coming from. I need to do a check here to make sure I'm not reading past // image data. // This seems to not be a big issue right now. (04/04/98) dctArray1[a][b] = inputArray[ypos + yblockoffset + a][xpos + xblockoffset + b]; } } // The following code commented out because on some images this technique // results in poor right an¢ì bottom borders. // if ((!JpegObj.lastColumnIsDummy[comp] || c < Width - 1) && (!JpegObj.lastRowIsDummy[comp] || r < Height - 1)) { dctArray2 = dct.forwardDCT(dctArray1); dctArray3 = dct.quantizeBlock(dctArray2, JpegObj.QtableNumber[comp]); // } // else { // zeroArray[0] = dctArray3[0]; // zeroArray[0] = lastDCvalue[comp]; // dctArray3 = zeroArray; // } Huf.HuffmanBlockEncoder(outStream, dctArray3, lastDCvalue[comp], JpegObj.DCtableNumber[comp], JpegObj.ACtableNumber[comp]); lastDCvalue[comp] = dctArray3[0]; } } } } } Huf.flushBuffer(outStream); } public void WriteEOI(BufferedOutputStream out) { byte[] EOI = {(byte) 0xFF, (byte) 0xD9}; WriteMarker(EOI, out); } public void WriteHeaders(BufferedOutputStream out) { int i, j, index, offset, length; int tempArray[]; // the SOI marker byte[] SOI = {(byte) 0xFF, (byte) 0xD8}; WriteMarker(SOI, out); // The order of the following headers is quiet inconsequential. // the JFIF header byte JFIF[] = new byte[18]; JFIF[0] = (byte) 0xff; JFIF[1] = (byte) 0xe0; JFIF[2] = (byte) 0x00; JFIF[3] = (byte) 0x10; JFIF[4] = (byte) 0x4a; JFIF[5] = (byte) 0x46; JFIF[6] = (byte) 0x49; JFIF[7] = (byte) 0x46; JFIF[8] = (byte) 0x00; JFIF[9] = (byte) 0x01; JFIF[10] = (byte) 0x00; JFIF[11] = (byte) 0x00; JFIF[12] = (byte) 0x00; JFIF[13] = (byte) 0x01; JFIF[14] = (byte) 0x00; JFIF[15] = (byte) 0x01; JFIF[16] = (byte) 0x00; JFIF[17] = (byte) 0x00; WriteArray(JFIF, out); // Comment Header String comment = new String(); comment = JpegObj.getComment(); length = comment.length(); byte COM[] = new byte[length + 4]; COM[0] = (byte) 0xFF; COM[1] = (byte) 0xFE; COM[2] = (byte) ((length >> 8) & 0xFF); COM[3] = (byte) (length & 0xFF); java.lang.System.arraycopy(JpegObj.Comment.getBytes(), 0, COM, 4, JpegObj.Comment.length()); WriteArray(COM, out); // The DQT header // 0 is the luminance index an¢ì 1 is the chrominance index byte DQT[] = new byte[134]; DQT[0] = (byte) 0xFF; DQT[1] = (byte) 0xDB; DQT[2] = (byte) 0x00; DQT[3] = (byte) 0x84; offset = 4; for (i = 0; i < 2; i++) { DQT[offset++] = (byte) ((0 << 4) + i); tempArray = (int[]) dct.quantum[i]; for (j = 0; j < 64; j++) { DQT[offset++] = (byte) tempArray[jpegNaturalOrder[j]]; } } WriteArray(DQT, out); // Start of Frame Header byte SOF[] = new byte[19]; SOF[0] = (byte) 0xFF; SOF[1] = (byte) 0xC0; SOF[2] = (byte) 0x00; SOF[3] = (byte) 17; SOF[4] = (byte) JpegObj.Precision; SOF[5] = (byte) ((JpegObj.imageHeight >> 8) & 0xFF); SOF[6] = (byte) ((JpegObj.imageHeight) & 0xFF); SOF[7] = (byte) ((JpegObj.imageWidth >> 8) & 0xFF); SOF[8] = (byte) ((JpegObj.imageWidth) & 0xFF); SOF[9] = (byte) JpegObj.NumberOfComponents; index = 10; for (i = 0; i < SOF[9]; i++) { SOF[index++] = (byte) JpegObj.CompID[i]; SOF[index++] = (byte) ((JpegObj.HsampFactor[i] << 4) + JpegObj.VsampFactor[i]); SOF[index++] = (byte) JpegObj.QtableNumber[i]; } WriteArray(SOF, out); // The DHT Header byte DHT1[], DHT2[], DHT3[], DHT4[]; int bytes, temp, oldindex, intermediateindex; length = 2; index = 4; oldindex = 4; DHT1 = new byte[17]; DHT4 = new byte[4]; DHT4[0] = (byte) 0xFF; DHT4[1] = (byte) 0xC4; for (i = 0; i < 4; i++ ) { bytes = 0; DHT1[index++ - oldindex] = (byte) ((int[]) Huf.bits.elementAt(i))[0]; for (j = 1; j < 17; j++) { temp = ((int[]) Huf.bits.elementAt(i))[j]; DHT1[index++ - oldindex] =(byte) temp; bytes += temp; } intermediateindex = index; DHT2 = new byte[bytes]; for (j = 0; j < bytes; j++) { DHT2[index++ - intermediateindex] = (byte) ((int[]) Huf.val.elementAt(i))[j]; } DHT3 = new byte[index]; java.lang.System.arraycopy(DHT4, 0, DHT3, 0, oldindex); java.lang.System.arraycopy(DHT1, 0, DHT3, oldindex, 17); java.lang.System.arraycopy(DHT2, 0, DHT3, oldindex + 17, bytes); DHT4 = DHT3; oldindex = index; } DHT4[2] = (byte) (((index - 2) >> 8)& 0xFF); DHT4[3] = (byte) ((index -2) & 0xFF); WriteArray(DHT4, out); // Start of Scan Header byte SOS[] = new byte[14]; SOS[0] = (byte) 0xFF; SOS[1] = (byte) 0xDA; SOS[2] = (byte) 0x00; SOS[3] = (byte) 12; SOS[4] = (byte) JpegObj.NumberOfComponents; index = 5; for (i = 0; i < SOS[4]; i++) { SOS[index++] = (byte) JpegObj.CompID[i]; SOS[index++] = (byte) ((JpegObj.DCtableNumber[i] << 4) + JpegObj.ACtableNumber[i]); } SOS[index++] = (byte) JpegObj.Ss; SOS[index++] = (byte) JpegObj.Se; SOS[index++] = (byte) ((JpegObj.Ah << 4) + JpegObj.Al); WriteArray(SOS, out); } void WriteMarker(byte[] data, BufferedOutputStream out) { try { out.write(data, 0, 2); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } void WriteArray(byte[] data, BufferedOutputStream out) { int i, length; try { length = (((int) (data[2] & 0xFF)) << 8) + (int) (data[3] & 0xFF) + 2; out.write(data, 0, length); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } // This class incorporates quality scaling as implemented in the JPEG-6a // library. /* * DCT - A Java implementation of the Discreet Cosine Transform */ class DCT { /** * DCT Block Size - default 8 */ public int N = 8; /** * Image Quality (0-100) - default 80 (good image / good compression) */ public int QUALITY = 80; public Object quantum[] = new Object[2]; public Object Divisors[] = new Object[2]; /** * Quantitization Matrix for luminace. */ public int quantum_luminance[] = new int[N*N]; public double DivisorsLuminance[] = new double[N*N]; /** * Quantitization Matrix for chrominance. */ public int quantum_chrominance[] = new int[N*N]; public double DivisorsChrominance[] = new double[N*N]; /** * Constructs a new DCT object. Initializes the cosine transform matrix * these are used when computing the DCT an¢ì it's inverse. This also * initializes the run length counters an¢ì the ZigZag sequence. Note that * the image quality can be worse than 25 however the image will be * extemely pixelated, usually to a block size of N. * * @param QUALITY The quality of the image (0 worst - 100 best) * */ public DCT(int QUALITY) { initMatrix(QUALITY); } /* * This method sets up the quantization matrix for luminance and * chrominance using the Quality parameter. */ private void initMatrix(int quality) { double[] AANscaleFactor = { 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379}; int i; int j; int index; int Quality; int temp; // converting quality setting to that specified in the jpeg_quality_scaling // method in the IJG Jpeg-6a C libraries Quality = quality; if (Quality <= 0) Quality = 1; if (Quality > 100) Quality = 100; if (Quality < 50) Quality = 5000 / Quality; else Quality = 200 - Quality * 2; // Creating the luminance matrix quantum_luminance[0]=16; quantum_luminance[1]=11; quantum_luminance[2]=10; quantum_luminance[3]=16; quantum_luminance[4]=24; quantum_luminance[5]=40; quantum_luminance[6]=51; quantum_luminance[7]=61; quantum_luminance[8]=12; quantum_luminance[9]=12; quantum_luminance[10]=14; quantum_luminance[11]=19; quantum_luminance[12]=26; quantum_luminance[13]=58; quantum_luminance[14]=60; quantum_luminance[15]=55; quantum_luminance[16]=14; quantum_luminance[17]=13; quantum_luminance[18]=16; quantum_luminance[19]=24; quantum_luminance[20]=40; quantum_luminance[21]=57; quantum_luminance[22]=69; quantum_luminance[23]=56; quantum_luminance[24]=14; quantum_luminance[25]=17; quantum_luminance[26]=22; quantum_luminance[27]=29; quantum_luminance[28]=51; quantum_luminance[29]=87; quantum_luminance[30]=80; quantum_luminance[31]=62; quantum_luminance[32]=18; quantum_luminance[33]=22; quantum_luminance[34]=37; quantum_luminance[35]=56; quantum_luminance[36]=68; quantum_luminance[37]=109; quantum_luminance[38]=103; quantum_luminance[39]=77; quantum_luminance[40]=24; quantum_luminance[41]=35; quantum_luminance[42]=55; quantum_luminance[43]=64; quantum_luminance[44]=81; quantum_luminance[45]=104; quantum_luminance[46]=113; quantum_luminance[47]=92; quantum_luminance[48]=49; quantum_luminance[49]=64; quantum_luminance[50]=78; quantum_luminance[51]=87; quantum_luminance[52]=103; quantum_luminance[53]=121; quantum_luminance[54]=120; quantum_luminance[55]=101; quantum_luminance[56]=72; quantum_luminance[57]=92; quantum_luminance[58]=95; quantum_luminance[59]=98; quantum_luminance[60]=112; quantum_luminance[61]=100; quantum_luminance[62]=103; quantum_luminance[63]=99; for (j = 0; j < 64; j++) { temp = (quantum_luminance[j] * Quality + 50) / 100; if ( temp <= 0) temp = 1; if (temp > 255) temp = 255; quantum_luminance[j] = temp; } index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The divisors for the LL&M method (the slow integer method used in // jpeg 6a library). This method is currently (04/04/98) incompletely // implemented. // DivisorsLuminance[index] = ((double) quantum_luminance[index]) << 3; // The divisors for the AAN method (the float method used in jpeg 6a library. DivisorsLuminance[index] = (double) ((double)1.0/((double) quantum_luminance[index] * AANscaleFactor[i] * AANscaleFactor[j] * (double) 8.0)); index++; } } // Creating the chrominance matrix quantum_chrominance[0]=17; quantum_chrominance[1]=18; quantum_chrominance[2]=24; quantum_chrominance[3]=47; quantum_chrominance[4]=99; quantum_chrominance[5]=99; quantum_chrominance[6]=99; quantum_chrominance[7]=99; quantum_chrominance[8]=18; quantum_chrominance[9]=21; quantum_chrominance[10]=26; quantum_chrominance[11]=66; quantum_chrominance[12]=99; quantum_chrominance[13]=99; quantum_chrominance[14]=99; quantum_chrominance[15]=99; quantum_chrominance[16]=24; quantum_chrominance[17]=26; quantum_chrominance[18]=56; quantum_chrominance[19]=99; quantum_chrominance[20]=99; quantum_chrominance[21]=99; quantum_chrominance[22]=99; quantum_chrominance[23]=99; quantum_chrominance[24]=47; quantum_chrominance[25]=66; quantum_chrominance[26]=99; quantum_chrominance[27]=99; quantum_chrominance[28]=99; quantum_chrominance[29]=99; quantum_chrominance[30]=99; quantum_chrominance[31]=99; quantum_chrominance[32]=99; quantum_chrominance[33]=99; quantum_chrominance[34]=99; quantum_chrominance[35]=99; quantum_chrominance[36]=99; quantum_chrominance[37]=99; quantum_chrominance[38]=99; quantum_chrominance[39]=99; quantum_chrominance[40]=99; quantum_chrominance[41]=99; quantum_chrominance[42]=99; quantum_chrominance[43]=99; quantum_chrominance[44]=99; quantum_chrominance[45]=99; quantum_chrominance[46]=99; quantum_chrominance[47]=99; quantum_chrominance[48]=99; quantum_chrominance[49]=99; quantum_chrominance[50]=99; quantum_chrominance[51]=99; quantum_chrominance[52]=99; quantum_chrominance[53]=99; quantum_chrominance[54]=99; quantum_chrominance[55]=99; quantum_chrominance[56]=99; quantum_chrominance[57]=99; quantum_chrominance[58]=99; quantum_chrominance[59]=99; quantum_chrominance[60]=99; quantum_chrominance[61]=99; quantum_chrominance[62]=99; quantum_chrominance[63]=99; for (j = 0; j < 64; j++) { temp = (quantum_chrominance[j] * Quality + 50) / 100; if ( temp <= 0) temp = 1; if (temp >= 255) temp = 255; quantum_chrominance[j] = temp; } index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The divisors for the LL&M method (the slow integer method used in // jpeg 6a library). This method is currently (04/04/98) incompletely // implemented. // DivisorsChrominance[index] = ((double) quantum_chrominance[index]) << 3; // The divisors for the AAN method (the float method used in jpeg 6a library. DivisorsChrominance[index] = (double) ((double)1.0/((double) quantum_chrominance[index] * AANscaleFactor[i] * AANscaleFactor[j] * (double)8.0)); index++; } } // quantum an¢ì Divisors are objects used to hold the appropriate matices quantum[0] = quantum_luminance; Divisors[0] = DivisorsLuminance; quantum[1] = quantum_chrominance; Divisors[1] = DivisorsChrominance; } /* * This method preforms forward DCT on a block of image data using * the literal method specified for a 2-D Discrete Cosine Transform. * It is included as a curiosity and can give you an idea of the * difference in the compression result (the resulting image quality) * by comparing its output to the output of the AAN method below. * It is ridiculously inefficient. */ // For now the final output is unusable. The associated quantization step // needs some tweaking. If you get this part working, please let me know. public double[][] forwardDCTExtreme(float input[][]) { double output[][] = new double[N][N]; double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; double tmp10, tmp11, tmp12, tmp13; double z1, z2, z3, z4, z5, z11, z13; int i; int j; int v, u, x, y; for (v = 0; v < 8; v++) { for (u = 0; u < 8; u++) { for (x = 0; x < 8; x++) { for (y = 0; y < 8; y++) { output[v][u] += ((double)input[x][y])*Math.cos(((double)(2*x + 1)*(double)u*Math.PI)/(double)16)*Math.cos(((double)(2*y + 1)*(double)v*Math.PI)/(double)16); } } output[v][u] *= (double)(0.25)*((u == 0) ? ((double)1.0/Math.sqrt(2)) : (double) 1.0)*((v == 0) ? ((double)1.0/Math.sqrt(2)) : (double) 1.0); } } return output; } /* * This method preforms a DCT on a block of image data using the AAN * method as implemented in the IJG Jpeg-6a library. */ public double[][] forwardDCT(float input[][]) { double output[][] = new double[N][N]; double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; double tmp10, tmp11, tmp12, tmp13; double z1, z2, z3, z4, z5, z11, z13; int i; int j; // Subtracts 128 from the input values for (i = 0; i < 8; i++) { for(j = 0; j < 8; j++) { output[i][j] = ((double)input[i][j] - (double)128.0); // input[i][j] -= 128; } } for (i = 0; i < 8; i++) { tmp0 = output[i][0] + output[i][7]; tmp7 = output[i][0] - output[i][7]; tmp1 = output[i][1] + output[i][6]; tmp6 = output[i][1] - output[i][6]; tmp2 = output[i][2] + output[i][5]; tmp5 = output[i][2] - output[i][5]; tmp3 = output[i][3] + output[i][4]; tmp4 = output[i][3] - output[i][4]; tmp10 = tmp0 + tmp3; tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; output[i][0] = tmp10 + tmp11; output[i][4] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * (double) 0.707106781; output[i][2] = tmp13 + z1; output[i][6] = tmp13 - z1; tmp10 = tmp4 + tmp5; tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; z5 = (tmp10 - tmp12) * (double) 0.382683433; z2 = ((double) 0.541196100) * tmp10 + z5; z4 = ((double) 1.306562965) * tmp12 + z5; z3 = tmp11 * ((double) 0.707106781); z11 = tmp7 + z3; z13 = tmp7 - z3; output[i][5] = z13 + z2; output[i][3] = z13 - z2; output[i][1] = z11 + z4; output[i][7] = z11 - z4; } for (i = 0; i < 8; i++) { tmp0 = output[0][i] + output[7][i]; tmp7 = output[0][i] - output[7][i]; tmp1 = output[1][i] + output[6][i]; tmp6 = output[1][i] - output[6][i]; tmp2 = output[2][i] + output[5][i]; tmp5 = output[2][i] - output[5][i]; tmp3 = output[3][i] + output[4][i]; tmp4 = output[3][i] - output[4][i]; tmp10 = tmp0 + tmp3; tmp13 = tmp0 - tmp3; tmp11 = tmp1 + tmp2; tmp12 = tmp1 - tmp2; output[0][i] = tmp10 + tmp11; output[4][i] = tmp10 - tmp11; z1 = (tmp12 + tmp13) * (double) 0.707106781; output[2][i] = tmp13 + z1; output[6][i] = tmp13 - z1; tmp10 = tmp4 + tmp5; tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; z5 = (tmp10 - tmp12) * (double) 0.382683433; z2 = ((double) 0.541196100) * tmp10 + z5; z4 = ((double) 1.306562965) * tmp12 + z5; z3 = tmp11 * ((double) 0.707106781); z11 = tmp7 + z3; z13 = tmp7 - z3; output[5][i] = z13 + z2; output[3][i] = z13 - z2; output[1][i] = z11 + z4; output[7][i] = z11 - z4; } return output; } /* * This method quantitizes data an¢ì rounds it to the nearest integer. */ public int[] quantizeBlock(double inputData[][], int code) { int outputData[] = new int[N*N]; int i, j; int index; index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { // The second line results in significantly better compression. outputData[index] = (int)(Math.round(inputData[i][j] * (((double[]) (Divisors[code]))[index]))); // outputData[index] = (int)(((inputData[i][j] * (((double[]) (Divisors[code]))[index])) + 16384.5) -16384); index++; } } return outputData; } /* * This is the method for quantizing a block DCT'ed with forwardDCTExtreme * This method quantitizes data an¢ì rounds it to the nearest integer. */ public int[] quantizeBlockExtreme(double inputData[][], int code) { int outputData[] = new int[N*N]; int i, j; int index; index = 0; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { outputData[index] = (int)(Math.round(inputData[i][j] / (double)(((int[]) (quantum[code]))[index]))); index++; } } return outputData; } } // This class was modified by James R. Weeks on 3/27/98. // It now incorporates Huffman table derivation as in the C jpeg library // from the IJG, Jpeg-6a. class Huffman { int bufferPutBits, bufferPutBuffer; public int ImageHeight; public int ImageWidth; public int DC_matrix0[][]; public int AC_matrix0[][]; public int DC_matrix1[][]; public int AC_matrix1[][]; public Object DC_matrix[]; public Object AC_matrix[]; public int code; public int NumOfDCTables; public int NumOfACTables; public int[] bitsDCluminance = { 0x00, 0, 1, 5, 1, 1,1,1,1,1,0,0,0,0,0,0,0}; public int[] valDCluminance = { 0,1,2,3,4,5,6,7,8,9,10,11 }; public int[] bitsDCchrominance = { 0x01,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 }; public int[] valDCchrominance = { 0,1,2,3,4,5,6,7,8,9,10,11 }; public int[] bitsACluminance = {0x10,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d }; public int[] valACluminance = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; public int[] bitsACchrominance = { 0x11,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77 };; public int[] valACchrominance = { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; public Vector bits; public Vector val; /* * The Huffman class constructor */ public Huffman(int Width,int Height) { bits = new Vector(); bits.addElement(bitsDCluminance); bits.addElement(bitsACluminance); bits.addElement(bitsDCchrominance); bits.addElement(bitsACchrominance); val = new Vector(); val.addElement(valDCluminance); val.addElement(valACluminance); val.addElement(valDCchrominance); val.addElement(valACchrominance); initHuf(); //code=code; ImageWidth=Width; ImageHeight=Height; } /** * HuffmanBlockEncoder run length encodes an¢ì Huffman encodes the quantized * data. **/ public void HuffmanBlockEncoder(BufferedOutputStream outStream, int zigzag[], int prec, int DCcode, int ACcode) { int temp, temp2, nbits, k, r, i; NumOfDCTables = 2; NumOfACTables = 2; // The DC portion temp = temp2 = zigzag[0] - prec; if(temp < 0) { temp = -temp; temp2--; } nbits = 0; while (temp != 0) { nbits++; temp >>= 1; } // if (nbits > 11) nbits = 11; bufferIt(outStream, ((int[][])DC_matrix[DCcode])[nbits][0], ((int[][])DC_matrix[DCcode])[nbits][1]); // The arguments in bufferIt are code an¢ì size. if (nbits != 0) { bufferIt(outStream, temp2, nbits); } // The AC portion r = 0; for (k = 1; k < 64; k++) { if ((temp = zigzag[jpegNaturalOrder[k]]) == 0) { r++; } else { while (r > 15) { bufferIt(outStream, ((int[][])AC_matrix[ACcode])[0xF0][0], ((int[][])AC_matrix[ACcode])[0xF0][1]); r -= 16; } temp2 = temp; if (temp < 0) { temp = -temp; temp2--; } nbits = 1; while ((temp >>= 1) != 0) { nbits++; } i = (r << 4) + nbits; bufferIt(outStream, ((int[][])AC_matrix[ACcode])[i][0], ((int[][])AC_matrix[ACcode])[i][1]); bufferIt(outStream, temp2, nbits); r = 0; } } if (r > 0) { bufferIt(outStream, ((int[][])AC_matrix[ACcode])[0][0], ((int[][])AC_matrix[ACcode])[0][1]); } } // Uses an integer long (32 bits) buffer to store the Huffman encoded bits // an¢ì sends them to outStream by the byte. void bufferIt(BufferedOutputStream outStream, int code,int size) { int PutBuffer = code; int PutBits = bufferPutBits; PutBuffer &= (1 << size) - 1; PutBits += size; PutBuffer <<= 24 - PutBits; PutBuffer |= bufferPutBuffer; while(PutBits >= 8) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } if (c == 0xFF) { try { outStream.write(0); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } PutBuffer <<= 8; PutBits -= 8; } bufferPutBuffer = PutBuffer; bufferPutBits = PutBits; } void flushBuffer(BufferedOutputStream outStream) { int PutBuffer = bufferPutBuffer; int PutBits = bufferPutBits; while (PutBits >= 8) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } if (c == 0xFF) { try { outStream.write(0); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } PutBuffer <<= 8; PutBits -= 8; } if (PutBits > 0) { int c = ((PutBuffer >> 16) & 0xFF); try { outStream.write(c); } catch (IOException e) { System.out.println("IO Error: " + e.getMessage()); } } } /* * Initialisation of the Huffman codes for Luminance an¢ì Chrominance. * This code results in the same tables created in the IJG Jpeg-6a * library. */ public void initHuf() { DC_matrix0=new int[12][2]; DC_matrix1=new int[12][2]; AC_matrix0=new int[255][2]; AC_matrix1=new int[255][2]; DC_matrix = new Object[2]; AC_matrix = new Object[2]; int p, l, i, lastp, si, code; int[] huffsize = new int[257]; int[] huffcode= new int[257]; /* * init of the DC values for the chrominance * [][0] is the code [][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsDCchrominance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { DC_matrix1[valDCchrominance[p]][0] = huffcode[p]; DC_matrix1[valDCchrominance[p]][1] = huffsize[p]; } /* * Init of the AC hufmann code for the chrominance * matrix [][][0] is the code & matrix[][][1] is the number of bit needed */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsACchrominance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { AC_matrix1[valACchrominance[p]][0] = huffcode[p]; AC_matrix1[valACchrominance[p]][1] = huffsize[p]; } /* * init of the DC values for the luminance * [][0] is the code [][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsDCluminance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (p = 0; p < lastp; p++) { DC_matrix0[valDCluminance[p]][0] = huffcode[p]; DC_matrix0[valDCluminance[p]][1] = huffsize[p]; } /* * Init of the AC hufmann code for luminance * matrix [][][0] is the code & matrix[][][1] is the number of bit */ p = 0; for (l = 1; l <= 16; l++) { for (i = 1; i <= bitsACluminance[l]; i++) { huffsize[p++] = l; } } huffsize[p] = 0; lastp = p; code = 0; si = huffsize[0]; p = 0; while(huffsize[p] != 0) { while(huffsize[p] == si) { huffcode[p++] = code; code++; } code <<= 1; si++; } for (int q = 0; q < lastp; q++) { AC_matrix0[valACluminance[q]][0] = huffcode[q]; AC_matrix0[valACluminance[q]][1] = huffsize[q]; } DC_matrix[0] = DC_matrix0; DC_matrix[1] = DC_matrix1; AC_matrix[0] = AC_matrix0; AC_matrix[1] = AC_matrix1; } } /* * JpegInfo - Given an image, sets default information about it an¢ì divides * it into its constituant components, downsizing those that need to be. */ class JpegInfo { String Comment; public Image imageobj; public int imageHeight; public int imageWidth; public int BlockWidth[]; public int BlockHeight[]; // the following are set as the default public int Precision = 8; public int NumberOfComponents = 3; public Object Components[]; public int[] CompID = {1, 2, 3}; public int[] HsampFactor = {1, 1, 1}; public int[] VsampFactor = {1, 1, 1}; public int[] QtableNumber = {0, 1, 1}; public int[] DCtableNumber = {0, 1, 1}; public int[] ACtableNumber = {0, 1, 1}; public boolean[] lastColumnIsDummy = {false, false, false}; public boolean[] lastRowIsDummy = {false, false, false}; public int Ss = 0; public int Se = 63; public int Ah = 0; public int Al = 0; public int compWidth[], compHeight[]; public int MaxHsampFactor; public int MaxVsampFactor; public JpegInfo(Image image) { Components = new Object[NumberOfComponents]; compWidth = new int[NumberOfComponents]; compHeight = new int[NumberOfComponents]; BlockWidth = new int[NumberOfComponents]; BlockHeight = new int[NumberOfComponents]; imageobj = image; imageWidth = image.getWidth(null); imageHeight = image.getHeight(null); Comment = "JPEG Encoder Copyright 1998, James R. Weeks an¢ì BioElectroMech. "; getYCCArray(); } public void setComment(String comment) { Comment.concat(comment); } public String getComment() { return Comment; } /* * This method creates an¢ì fills three arrays, Y, Cb, an¢ì Cr using the * input image. */ private void getYCCArray() { int values[] = new int[imageWidth * imageHeight]; int r, g, b, y, x; // In order to minimize the chance that grabPixels will throw an exception // it may be necessary to grab some pixels every few scanlines an¢ì process // those before going for more. The time expense may be prohibitive. // However, for a situation where memory overhead is a concern, this may be // the only choice. PixelGrabber grabber = new PixelGrabber(imageobj.getSource(), 0, 0, imageWidth, imageHeight, values, 0, imageWidth); MaxHsampFactor = 1; MaxVsampFactor = 1; for (y = 0; y < NumberOfComponents; y++) { MaxHsampFactor = Math.max(MaxHsampFactor, HsampFactor[y]); MaxVsampFactor = Math.max(MaxVsampFactor, VsampFactor[y]); } for (y = 0; y < NumberOfComponents; y++) { compWidth[y] = (((imageWidth%8 != 0) ? ((int) Math.ceil((double) imageWidth/8.0))*8 : imageWidth)/MaxHsampFactor)*HsampFactor[y]; if (compWidth[y] != ((imageWidth/MaxHsampFactor)*HsampFactor[y])) { lastColumnIsDummy[y] = true; } // results in a multiple of 8 for compWidth // this will make the rest of the program fail for the unlikely // event that someone tries to compress an 16 x 16 pixel image // which would of course be worse than pointless BlockWidth[y] = (int) Math.ceil((double) compWidth[y]/8.0); compHeight[y] = (((imageHeight%8 != 0) ? ((int) Math.ceil((double) imageHeight/8.0))*8: imageHeight)/MaxVsampFactor)*VsampFactor[y]; if (compHeight[y] != ((imageHeight/MaxVsampFactor)*VsampFactor[y])) { lastRowIsDummy[y] = true; } BlockHeight[y] = (int) Math.ceil((double) compHeight[y]/8.0); } try { if(grabber.grabPixels() != true) { try { throw new AWTException("Grabber returned false: " + grabber.status()); } catch (Exception e) {}; } } catch (InterruptedException e) {}; float Y[][] = new float[compHeight[0]][compWidth[0]]; float Cr1[][] = new float[compHeight[0]][compWidth[0]]; float Cb1[][] = new float[compHeight[0]][compWidth[0]]; float Cb2[][] = new float[compHeight[1]][compWidth[1]]; float Cr2[][] = new float[compHeight[2]][compWidth[2]]; int index = 0; for (y = 0; y < imageHeight; ++y) { for (x = 0; x < imageWidth; ++x) { r = ((values[index] >> 16) & 0xff); g = ((values[index] >> 8) & 0xff); b = (values[index] & 0xff); // The following three lines are a more correct color conversion but // the current conversion technique is sufficient an¢ì results in a higher // compression rate. // Y[y][x] = 16 + (float)(0.8588*(0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b )); // Cb1[y][x] = 128 + (float)(0.8784*(-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b)); // Cr1[y][x] = 128 + (float)(0.8784*(0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b)); Y[y][x] = (float)((0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b)); Cb1[y][x] = 128 + (float)((-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b)); Cr1[y][x] = 128 + (float)((0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b)); index++; } } // Need a way to set the H an¢ì V sample factors before allowing downsampling. // For now (04/04/98) downsampling must be hard coded. // Until a better downsampler is implemented, this will not be done. // Downsampling is currently supported. The downsampling method here // is a simple box filter. Components[0] = Y; // Cb2 = DownSample(Cb1, 1); Components[1] = Cb1; // Cr2 = DownSample(Cr1, 2); Components[2] = Cr1; } float[][] DownSample(float[][] C, int comp) { int inrow, incol; int outrow, outcol; float output[][]; int temp; int bias; inrow = 0; incol = 0; output = new float[compHeight[comp]][compWidth[comp]]; for (outrow = 0; outrow < compHeight[comp]; outrow++) { bias = 1; for (outcol = 0; outcol < compWidth[comp]; outcol++) { output[outrow][outcol] = (C[inrow][incol++] + C[inrow++][incol--] + C[inrow][incol++] + C[inrow--][incol++] + (float)bias)/(float)4.0; bias ^= 3; } inrow += 2; incol = 0; } return output; } } /* LICENSE.TXT ************************************************************** The JpegEncoder an¢ì its associated classes are Copyright (c) 1998, James R. Weeks an¢ì BioElectroMech. This software is based in part on the work of the Independent JPEG Group. Redistribution an¢ì use in source an¢ì binary forms, with o¢ú 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, all files included with the source code, an¢ì the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions an¢ì the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR an¢ì CONTRIBUTORS ``AS IS'' AND ANY EXPRESS o¢ú IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY an¢ì FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR o¢ú CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS o¢ú SERVICES; LOSS OF USE, DATA, o¢ú PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED an¢ì ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, o¢ú 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. ****************************************************************************/ /* IJGREADME.TXT ************************************************************ The Independent JPEG Group's JPEG software ========================================== README for release 6a of 7-Feb-96 ================================= This distribution contains the sixth public release of the Independent JPEG Group's free JPEG software. You are welcome to redistribute this software and to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. Serious users of this software (particularly those incorporating it into larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to our electronic mailing list. Mailing list members are notified of updates and have a chance to participate in technical discussions, etc. This software is the work of Tom Lane, Philip Gladstone, Luis Ortiz, Jim Boucher, Lee Crocker, Julian Minguillon, George Phillips, Davide Rossi, Ge' Weijers, an¢ì other members of the Independent JPEG Group. IJG is not affiliated with the official ISO JPEG standards committee. DOCUMENTATION ROADMAP ===================== This file contains the following sections: OVERVIEW General description of JPEG an¢ì the IJG software. LEGAL ISSUES Copyright, lack of warranty, terms of distribution. REFERENCES Where to learn more about JPEG. ARCHIVE LOCATIONS Where to find newer versions of this software. RELATED SOFTWARE Other stuff you should get. FILE FORMAT WARS Software *not* to get. TO DO Plans for future IJG releases. Other documentation files in the distribution are: User documentation: install.doc How to configure an¢ì install the IJG software. usage.doc Usage instructions for cjpeg, djpeg, jpegtran, rdjpgcom, an¢ì wrjpgcom. *.1 Unix-style man pages for programs (same info as usage.doc). wizard.doc Advanced usage instructions for JPEG wizards only. change.log Version-to-version change highlights. Programmer an¢ì internal documentation: libjpeg.doc How to use the JPEG library in your own programs. example.c Sample code for calling the JPEG library. structure.doc Overview of the JPEG library's internal structure. filelist.doc Road map of IJG files. coderules.doc Coding style rules --- please read if you contribute code. Please read at least the files install.doc an¢ì usage.doc. Useful information can also be found in the JPEG FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. If you want to understand how the JPEG code works, we suggest reading one or more of the REFERENCES, then looking at the documentation files (in roughly the order listed) before diving into the code. OVERVIEW ======== This package contains C software to implement JPEG image compression and decompression. JPEG (pronounced "jay-peg") is a standardized compression method for full-color an¢ì gray-scale images. JPEG is intended for compressing "real-world" scenes; line drawings, cartoons an¢ì other non-realistic images are not its strong suit. JPEG is lossy, meaning that the output image is not exactly identical to the input image. Hence you must not use JPEG if you have to have identical output bits. However, on typical photographic images, very good compression levels can be obtained with no visible change, and remarkably high compression levels are possible if you can tolerate a low-quality image. For more details, see the references, o¢ú just experiment with various compression settings. This software implements JPEG baseline, extended-sequential, an¢ì progressive compression processes. Provision is made for supporting all variants of these processes, although some uncommon parameter settings aren't implemented yet. For legal reasons, we are not distributing code for the arithmetic-coding variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting the hierarchical o¢ú lossless processes defined in the standard. We provide a set of library routines for reading an¢ì writing JPEG image files, plus two sample applications "cjpeg" an¢ì "djpeg", which use the library to perform conversion between JPEG an¢ì some other popular image file formats. The library is intended to be reused in other applications. In order to support file conversion an¢ì viewing software, we have included considerable functionality beyond the bare JPEG coding/decoding capability; for example, the color quantization modules are not strictly part of JPEG decoding, but they are essential for output to colormapped file formats or colormapped displays. These extra functions can be compiled out of the library if not required for a particular application. We have also included "jpegtran", a utility for lossless transcoding between different JPEG processes, an¢ì "rdjpgcom" an¢ì "wrjpgcom", two simple applications for inserting an¢ì extracting textual comments in JFIF files. The emphasis in designing this software has been on achieving portability and flexibility, while also making it fast enough to be useful. In particular, the software is not intended to be read as a tutorial on JPEG. (See the REFERENCES section for introductory material.) Rather, it is intended to be reliable, portable, industrial-strength code. We do not claim to have achieved that goal in every aspect of the software, but we strive for it. We welcome the use of this software as a component of commercial products. No royalty is required, but we do ask for an acknowledgement in product documentation, as described under LEGAL ISSUES. LEGAL ISSUES ============ In plain English: 1. We don't promise that this software works. (But if you find any bugs, please let us know!) 2. You can use this software for whatever you want. You don't have to pay us. 3. You may not pretend that you wrote this software. If you use it in a program, you must acknowledge somewhere in your documentation that you've used the IJG code. In legalese: The authors make NO WARRANTY o¢ú representation, either express o¢ú implied, with respect to this software, its quality, accuracy, merchantability, or fitness for a particular purpose. This software is provided "AS IS", an¢ì you, its user, assume the entire risk as to its quality an¢ì accuracy. This software is copyright (C) 1991-1996, Thomas G. Lane. All Rights Reserved except as specified below. Permission is hereby granted to use, copy, modify, an¢ì distribute this software (or portions thereof) for any purpose, without fee, subject to these conditions: (1) If any part of the source code for this software is distributed, then this README file must be included, with this copyright an¢ì no-warranty notice unaltered; an¢ì any additions, deletions, o¢ú changes to the original files must be clearly indicated in accompanying documentation. (2) If only executable code is distributed, then the accompanying documentation must state that "this software is based in part on the work of the Independent JPEG Group". (3) Permission for use of this software is granted only if the user accepts full responsibility for any undesirable consequences; the authors accept NO LIABILITY for damages of any kind. These conditions apply to any software derived from o¢ú based on the IJG code, not just to the unmodified library. If you use our work, you ought to acknowledge us. Permission is NOT granted for the use of any IJG author's name o¢ú company name in advertising o¢ú publicity relating to this software o¢ú products derived from it. This software may be referred to only as "the Independent JPEG Group's software". We specifically permit an¢ì encourage the use of this software as the basis of commercial products, provided that all warranty o¢ú liability claims are assumed by the product vendor. ansi2knr.c is included in this distribution by permission of L. Peter Deutsch, sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA. ansi2knr.c is NOT covered by the above copyright an¢ì conditions, but instead by the usual distribution terms of the Free Software Foundation; principally, that you must include source code if you redistribute it. (See the file ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part of any program generated from the IJG code, this does not limit you more than the foregoing paragraphs do. The configuration script "configure" was produced with GNU Autoconf. It is copyright by the Free Software Foundation but is freely distributable. It appears that the arithmetic coding option of the JPEG spec is covered by patents owned by IBM, AT&T, an¢ì Mitsubishi. Hence arithmetic coding cannot legally be used without obtaining one o¢ú more licenses. For this reason, support for arithmetic coding has been removed from the free JPEG software. (Since arithmetic coding provides only a marginal gain over the unpatented Huffman mode, it is unlikely that very many implementations will support it.) So far as we are aware, there are no patent restrictions on the remaining code. WARNING: Unisys has begun to enforce their patent on LZW compression against GIF encoders an¢ì decoders. You will need a license from Unisys to use the included rdgif.c o¢ú wrgif.c files in a commercial o¢ú shareware application. At this time, Unisys is not enforcing their patent against freeware, so distribution of this package remains legal. However, we intend to remove GIF support from the IJG package as soon as a suitable replacement format becomes reasonably popular. We are required to state that "The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated." REFERENCES ========== We highly recommend reading one o¢ú more of these references before trying to understand the innards of the JPEG software. The best short technical introduction to the JPEG compression algorithm is Wallace, Gregory K. "The JPEG Still Picture Compression Standard", Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. (Adjacent articles in that issue discuss MPEG motion picture compression, applications of JPEG, an¢ì related topics.) If you don't have the CACM issue handy, a PostScript file containing a revised version of Wallace's article is available at ftp.uu.net, graphics/jpeg/wallace.ps.gz. The file (actually a preprint for an article that appeared in IEEE Trans. Consumer Electronics) omits the sample images that appeared in CACM, but it includes corrections and some added material. Note: the Wallace article is copyright ACM and IEEE, an¢ì it may not be used for commercial purposes. A somewhat less technical, more leisurely introduction to JPEG can be found in "The Data Compression Book" by Mark Nelson, published by M&T Books (Redwood City, CA), 1991, ISBN 1-55851-216-0. This book provides good explanations and example C code for a multitude of compression methods including JPEG. It is an excellent source if you are comfortable reading C code but don't know much about data compression in general. The book's JPEG sample code is far from industrial-strength, but when you are ready to look at a full implementation, you've got one here... The best full description of JPEG is the textbook "JPEG Still Image Data Compression Standard" by William B. Pennebaker an¢ì Joan L. Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG standards (DIS 10918-1 and draft DIS 10918-2). This is by far the most complete exposition of JPEG in existence, an¢ì we highly recommend it. The JPEG standard itself is not available electronically; you must order a paper copy through ISO o¢ú ITU. (Unless you feel a need to own a certified official copy, we recommend buying the Pennebaker an¢ì Mitchell book instead; it's much cheaper an¢ì includes a great deal of useful explanatory material.) In the USA, copies of the standard may be ordered from ANSI Sales at (212) 642-4900, o¢ú from Global Engineering Documents at (800) 854-7179. (ANSI doesn't take credit card orders, but Global does.) It's not cheap: as of 1992, ANSI was charging $95 for Part 1 an¢ì $47 for Part 2, plus 7% shipping/handling. The standard is divided into two parts, Part 1 being the actual specification, while Part 2 covers compliance testing methods. Part 1 is titled "Digital Compression an¢ì Coding of Continuous-tone Still Images, Part 1: Requirements an¢ì guidelines" an¢ì has document numbers ISO/IEC IS 10918-1, ITU-T T.81. Part 2 is titled "Digital Compression an¢ì Coding of Continuous-tone Still Images, Part 2: Compliance testing" an¢ì has document numbers ISO/IEC IS 10918-2, ITU-T T.83. Extensions to the original JPEG standard are defined in JPEG Part 3, a new ISO document. Part 3 is undergoing ISO balloting an¢ì is expected to be approved by the end of 1995; it will have document numbers ISO/IEC IS 10918-3, ITU-T T.84. IJG currently does not support any Part 3 extensions. The JPEG standard does not specify all details of an interchangeable file format. For the omitted details we follow the "JFIF" conventions, revision 1.02. A copy of the JFIF spec is available from: Literature Department C-Cube Microsystems, Inc. 1778 McCarthy Blvd. Milpitas, CA 95035 phone (408) 944-6300, fax (408) 944-6314 A PostScript version of this document is available at ftp.uu.net, file graphics/jpeg/jfif.ps.gz. It can also be obtained by e-mail from the C-Cube mail server, netlib@c3.pla.ca.us. Send the message "send jfif_ps from jpeg" to the server to obtain the JFIF document; send the message "help" if you have trouble. The TIFF 6.0 file format specification can be obtained by FTP from sgi.com (192.48.153.1), file graphics/tiff/TIFF6.ps.Z; o¢ú you can order a printed copy from Aldus Corp. at (206) 628-6593. The JPEG incorporation scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 (Compression tag 7). Copies of this Note can be obtained from sgi.com or from ftp.uu.net:/graphics/jpeg/. It is expected that the next revision of the TIFF spec will replace the 6.0 JPEG design with the Note's design. Although IJG's own code does not support TIFF/JPEG, the free libtiff library uses our library to implement TIFF/JPEG per the Note. libtiff is available from sgi.com:/graphics/tiff/. ARCHIVE LOCATIONS ================= The "official" archive site for this software is ftp.uu.net (Internet address 192.48.96.9). The most recent released version can always be found there in directory graphics/jpeg. This particular version will be archived as graphics/jpeg/jpegsrc.v6a.tar.gz. If you are on the Internet, you can retrieve files from ftp.uu.net by standard anonymous FTP. If you don't have FTP access, UUNET's archives are also available via UUCP; contact help@uunet.uu.net for information on retrieving files that way. Numerous Internet sites maintain copies of the UUNET files. However, only ftp.uu.net is guaranteed to have the latest official version. You can also obtain this software in DOS-compatible "zip" archive format from the SimTel archives (ftp.coast.net:/SimTel/msdos/graphics/), o¢ú on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12 "JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net release. The JPEG FAQ (Frequently Asked Questions) article is a useful source of general information about JPEG. It is updated constantly an¢ì therefore is not included in this distribution. The FAQ is posted every two weeks to Usenet newsgroups comp.graphics.misc, news.answers, an¢ì other groups. You can always obtain the latest version from the news.answers archive at rtfm.mit.edu. By FTP, fetch /pub/usenet/news.answers/jpeg-faq/part1 and .../part2. If you don't have FTP, send e-mail to mail-server@rtfm.mit.edu with body send usenet/news.answers/jpeg-faq/part1 send usenet/news.answers/jpeg-faq/part2 RELATED SOFTWARE ================ Numerous viewing an¢ì image manipulation programs now support JPEG. (Quite a few of them use this library to do so.) The JPEG FAQ described above lists some of the more popular free an¢ì shareware viewers, an¢ì tells where to obtain them on Internet. If you are on a Unix machine, we highly recommend Jef Poskanzer's free PBMPLUS image software, which provides many useful operations on PPM-format image files. In particular, it can convert PPM images to an¢ì from a wide range of other formats. You can obtain this package by FTP from ftp.x.org (contrib/pbmplus*.tar.Z) o¢ú ftp.ee.lbl.gov (pbmplus*.tar.Z). There is also a newer updat¢í of this package called NETPBM, available from wuarchive.wustl.edu under directory /graphics/graphics/packages/NetPBM/. Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is; you are likely to have difficulty making it work on any non-Unix machine. A different free JPEG implementation, written by the PVRG group at Stanford, is available from havefun.stanford.edu in directory pub/jpeg. This program is designed for research an¢ì experimentation rather than production use; it is slower, harder to use, an¢ì less portable than the IJG code, but it is easier to read an¢ì modify. Also, the PVRG code supports lossless JPEG, which we do not. FILE FORMAT WARS ================ Some JPEG programs produce files that are not compatible with our library. The root of the problem is that the ISO JPEG committee failed to specify a concrete file format. Some vendors "filled in the blanks" on their own, creating proprietary formats that no one else could read. (For example, none of the early commercial JPEG implementations for the Macintosh were able to exchange compressed files.) The file format we have adopted is called JFIF (see REFERENCES). This format has been agreed to by a number of major commercial JPEG vendors, an¢ì it has become the de facto standard. JFIF is a minimal o¢ú "low end" representation. We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF Technical Note #2) for "high end" applications that need to record a lot of additional data about an image. TIFF/JPEG is fairly new an¢ì not yet widely supported, unfortunately. The upcoming JPEG Part 3 standard defines a file format called SPIFF. SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should be able to read the most common variant of SPIFF. SPIFF has some technical advantages over JFIF, but its major claim to fame is simply that it is an official standard rather than an informal one. At this point it is unclear whether SPIFF will supersede JFIF o¢ú whether JFIF will remain the de-facto standard. IJG intends to support SPIFF once the standard is frozen, but we have not decided whether it should become our default output format o¢ú not. (In any case, our decoder will remain capable of reading JFIF indefinitely.) Various proprietary file formats incorporating JPEG compression also exist. We have little o¢ú no sympathy for the existence of these formats. Indeed, one of the original reasons for developing this free software was to help force convergence on common, open format standards for JPEG files. Don't use a proprietary file format! TO DO ===== In future versions, we are considering supporting some of the upcoming JPEG Part 3 extensions --- principally, variable quantization an¢ì the SPIFF file format. Tuning the software for better behavior at low quality/high compression settings is also of interest. The current method for scaling the quantization tables is known not to be very good at low Q values. As always, speeding things up is high on our priority list. Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net. ****************************************************************************/
unlicense
hoolos/BreakTimeApp
BreakTimeApp/src/mymaps/managers/DatabaseManager.java
732
package mymaps.managers; import java.util.List; import mymaps.db.DatabaseHelperSQL; public abstract class DatabaseManager<V, DB extends DatabaseHelperSQL> { protected DB dbHelper; protected static final String TAG = "DB_MANAGER"; protected NotifyDownloadManager dManager; public abstract void deleteDataBase(); public abstract DB getDatabaseHelper(); public abstract V getFromDB(Object... params); public abstract void putToDB(final V item); public abstract void batchPutToDB(List<V> batch); public abstract void updateItem(Object... params); public void setNotifyDownloadManager(NotifyDownloadManager dManager) { this.dManager = dManager; } }
unlicense
rulojuka/listas
mac0242/Saida.java
515
import java.util.*; import java.io.*; public class Saida extends Objeto { Lugar destino; boolean aberta = true; Saida(String Nome) { this(Nome, ""); } Saida(String Nome, String C) { this(Nome, C,""); } Saida(String Nome, String C, String L) { super(Nome, C, L); // o default é não ser visível, a saída aparece na descrição do lugar visivel = false; } void Abre() {aberta = true;} void Fecha() {aberta = false;} void Muda(Lugar l) {destino = l;} }
unlicense
hibernate/hibernate-demos
hibernate-search/hsearch-feature-examples/search-advanced/src/main/java/org/hibernate/demos/hsearchfeatureexamples/TShirtService.java
10215
package org.hibernate.demos.hsearchfeatureexamples; import java.math.BigDecimal; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.inject.Inject; import javax.json.JsonValue; import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import org.hibernate.demos.hsearchfeatureexamples.dto.PriceRangeDto; import org.hibernate.demos.hsearchfeatureexamples.dto.SearchResultDto; import org.hibernate.demos.hsearchfeatureexamples.dto.TShirtInputDto; import org.hibernate.demos.hsearchfeatureexamples.dto.TShirtOutputDto; import org.hibernate.demos.hsearchfeatureexamples.dto.mapper.TShirtMapper; import org.hibernate.demos.hsearchfeatureexamples.model.TShirt; import org.hibernate.demos.hsearchfeatureexamples.model.TShirtSize; import org.hibernate.search.backend.elasticsearch.ElasticsearchExtension; import org.hibernate.search.backend.elasticsearch.search.query.ElasticsearchSearchResult; import org.hibernate.search.engine.search.aggregation.AggregationKey; import org.hibernate.search.engine.search.common.BooleanOperator; import org.hibernate.search.engine.search.predicate.dsl.PredicateFinalStep; import org.hibernate.search.engine.search.predicate.dsl.SearchPredicateFactory; import org.hibernate.search.engine.search.query.SearchResult; import org.hibernate.search.mapper.orm.session.SearchSession; import org.hibernate.search.util.common.data.Range; import org.jboss.resteasy.annotations.jaxrs.PathParam; import org.jboss.resteasy.annotations.jaxrs.QueryParam; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.glassfish.json.JsonUtil; @Path("/tshirt") @Transactional public class TShirtService { private static final int PAGE_SIZE = 10; @Inject TShirtMapper mapper; @Inject SearchSession searchSession; private final Gson gson = new Gson(); @POST public TShirtOutputDto create(TShirtInputDto input) { TShirt entity = new TShirt(); mapper.input( entity, input ); TShirt.persist( entity ); return mapper.output( entity ); } @PUT @Path("{id}") public TShirtOutputDto update(@PathParam long id, TShirtInputDto input) { TShirt entity = find( id ); mapper.input( entity, input ); return mapper.output( entity ); } @GET @Path("{id}") public TShirtOutputDto retrieve(@PathParam long id) { TShirt entity = find( id ); return mapper.output( entity ); } @GET public List<TShirtOutputDto> list(@QueryParam int page, @QueryParam boolean brief) { List<TShirt> entities = TShirt.findAll() .page( page, PAGE_SIZE ).list(); return mapper.output( entities, brief ); } @GET @Path("search") public SearchResultDto<TShirtOutputDto> search(@QueryParam String q, @QueryParam int page, @QueryParam boolean brief) { SearchResult<TShirt> result = searchSession.search( TShirt.class ) .where( f -> { if ( q == null || q.isBlank() ) { return f.matchAll(); } else { return f.simpleQueryString() .fields( "name", "collection.keywords", "variants.color", "variants.size" ) .matching( q ); } } ) .fetch( page * PAGE_SIZE, PAGE_SIZE ); return new SearchResultDto<>( result.total().hitCount(), mapper.output( result.hits(), brief ) ); } @GET @Path("autocomplete") public List<TShirtOutputDto> autocomplete(@QueryParam String terms) { List<TShirt> hits = searchSession.search( TShirt.class ) .where( f -> f.simpleQueryString() .fields( "name_autocomplete" ) .matching( terms ) .defaultOperator( BooleanOperator.AND ) ) .fetchHits( PAGE_SIZE ); return mapper.outputBrief( hits ); } @GET @Path("autocomplete_nodb") public List<TShirtOutputDto> autocompleteNoDatabase(@QueryParam String terms) { return searchSession.search( TShirt.class ) .select( f -> f.composite( (ref, field) -> TShirtOutputDto.of( (long) ref.id(), field ), f.entityReference(), f.field( "name", String.class ) ) ) .where( f -> f.simpleQueryString() .fields( "name_autocomplete" ) .matching( terms ) .defaultOperator( BooleanOperator.AND ) ) .fetchHits( PAGE_SIZE ); } @GET @Path("search_facets") public SearchResultDto<TShirtOutputDto> searchWithFacets(@QueryParam String q, @QueryParam String color, @QueryParam TShirtSize size, @QueryParam PriceRangeDto priceRange, @QueryParam int page, @QueryParam boolean brief) { AggregationKey<Map<String, Long>> countByColor = AggregationKey.of( "count-by-color" ); AggregationKey<Map<TShirtSize, Long>> countBySize = AggregationKey.of( "count-by-size" ); AggregationKey<Map<Range<BigDecimal>, Long>> countByPriceRange = AggregationKey.of( "count-by-price-range" ); SearchResult<TShirt> result = searchSession.search( TShirt.class ) .where( f -> f.bool( b -> { b.must( f.matchAll() ); // Match all by default if ( q != null && !q.isBlank() ) { b.must( f.simpleQueryString() .fields( "name", "collection.keywords", "variants_nested.color", "variants_nested.size" ) .matching( q ) ); } if ( color != null || size != null || priceRange != null ) { b.must( f.nested().objectField( "variants_nested" ) .nest( variantFilter( f, size, color, priceRange ) ) ); } } ) ) .aggregation( countByColor, f -> f.terms() .field( "variants_nested.color_keyword", String.class ) .filter( f2 -> variantFilter( f2, size, color, priceRange ) ) .orderByTermAscending() .minDocumentCount( 0 ) ) .aggregation( countBySize, f -> f.terms() .field( "variants_nested.size_keyword", TShirtSize.class ) .filter( f2 -> variantFilter( f2, size, color, priceRange ) ) .orderByTermAscending() .minDocumentCount( 0 ) ) .aggregation( countByPriceRange, f -> f.range() .field( "variants_nested.price", BigDecimal.class ) .ranges( EnumSet.allOf( PriceRangeDto.class ) .stream().map( r -> r.value ) .collect( Collectors.toList() ) ) .filter( f2 -> variantFilter( f2, size, color, priceRange ) ) ) .fetch( page * PAGE_SIZE, PAGE_SIZE ); return new SearchResultDto<>( result.total().hitCount(), mapper.output( result.hits(), brief ), Map.of( countByColor.name(), result.aggregation( countByColor ), countBySize.name(), result.aggregation( countBySize ), countByPriceRange.name(), result.aggregation( countByPriceRange ) ) ); } private PredicateFinalStep variantFilter(SearchPredicateFactory f, TShirtSize size, String color, PriceRangeDto priceRange) { if ( size == null && color == null && priceRange == null ) { return f.matchAll(); } return f.bool( variantsBool -> { if ( color != null ) { variantsBool.must( f.match() .field( "variants_nested.color" ) .matching( color ) ); } if ( size != null ) { variantsBool.must( f.match() .field( "variants_nested.size" ) .matching( size ) ); } if ( priceRange != null ) { variantsBool.must( f.range() .field( "variants_nested.price" ) .range( priceRange.value ) ); } } ); } @GET @Path("pricestats") public JsonValue priceStats(@QueryParam String q) { AggregationKey<JsonObject> priceStats = AggregationKey.of( "price-stats" ); SearchResult<TShirt> result = searchSession.search( TShirt.class ) .extension( ElasticsearchExtension.get() ) .where( f -> { if ( q == null || q.isBlank() ) { return f.matchAll(); } else { return f.simpleQueryString() .fields( "name", "collection.keywords", "variants.color", "variants.size" ) .matching( q ); } } ) .aggregation( priceStats, f -> f.fromJson( "{\n" + " \"stats\": {\n" + " \"field\": \"variants.price\"\n" + " }\n" + "}" ) ) .fetch( 0 ); return JsonUtil.toJson( result.aggregation( priceStats ).toString() ); } @GET @Path("suggest") public JsonValue suggest(@QueryParam String terms) { ElasticsearchSearchResult<TShirt> result = searchSession.search( TShirt.class ) .extension( ElasticsearchExtension.get() ) .where( f -> f.matchAll() ) .requestTransformer( context -> { JsonObject body = context.body(); body.add( "suggest", jsonObject( suggest -> { suggest.addProperty( "text", terms ); suggest.add( "name-suggest-phrase", gson.fromJson( "{\n" + " \"phrase\": {\n" + " \"field\": \"name_suggest\",\n" + " \"size\": 2,\n" + " \"gram_size\": 3,\n" + " \"direct_generator\": [ {\n" + " \"field\": \"name_suggest\",\n" + " \"suggest_mode\": \"always\"\n" + " }, {\n" + " \"field\" : \"name_suggest_reverse\",\n" + " \"suggest_mode\" : \"always\",\n" + " \"pre_filter\" : \"suggest_reverse\",\n" + " \"post_filter\" : \"suggest_reverse\"\n" + " } ],\n" + " \"highlight\": {\n" + " \"pre_tag\": \"<em>\",\n" + " \"post_tag\": \"</em>\"\n" + " }\n" + " }\n" + "}", JsonObject.class ) ); } ) ); } ) .fetch( 0 ); JsonObject responseBody = result.responseBody(); JsonArray mySuggestResults = responseBody.getAsJsonObject( "suggest" ) .getAsJsonArray( "name-suggest-phrase" ); return JsonUtil.toJson( mySuggestResults.toString() ); } private TShirt find(long id) { TShirt entity = TShirt.findById( id ); if ( entity == null ) { throw new NotFoundException(); } return entity; } private static JsonObject jsonObject(Consumer<JsonObject> instructions) { JsonObject object = new JsonObject(); instructions.accept( object ); return object; } private static JsonArray jsonArray(JsonElement... elements) { JsonArray array = new JsonArray(); for ( JsonElement element : elements ) { array.add( element ); } return array; } }
apache-2.0
gijsleussink/ceylon
compiler-java/src/com/redhat/ceylon/ceylondoc/LinkRenderer.java
40706
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.ceylondoc; import static com.redhat.ceylon.ceylondoc.CeylondMessages.msg; import static com.redhat.ceylon.ceylondoc.Util.getAnnotation; import static com.redhat.ceylon.ceylondoc.Util.isAbbreviatedType; import static com.redhat.ceylon.ceylondoc.Util.normalizeSpaces; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateCallable; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateEntry; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateIterable; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateOptional; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateSequence; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateSequential; import static com.redhat.ceylon.model.typechecker.util.TypePrinter.abbreviateTuple; import java.io.File; import java.io.IOException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.compiler.java.codegen.Decl; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.model.loader.AbstractModelLoader; import com.redhat.ceylon.model.typechecker.model.Annotated; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Element; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.NothingType; import com.redhat.ceylon.model.typechecker.model.Package; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.Referenceable; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.TypeAlias; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.TypedDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.Value; import com.redhat.ceylon.model.typechecker.util.TypePrinter; public class LinkRenderer { private Object to; private Object from; private CeylonDocTool ceylonDocTool; private Writer writer; private String customText; private boolean withinText; private Referenceable scope; private String anchor; private boolean printAbbreviated = true; private boolean printTypeParameters = true; private boolean printTypeParameterDetail = false; private boolean printWikiStyleLinks = false; private boolean printLinkDropdownMenu = true; private boolean printParenthesisAfterMethodName = true; private boolean printMemberContainerName = true; private final TypePrinter producedTypeNamePrinter = new TypePrinter() { @Override public String getSimpleDeclarationName(Declaration declaration, Unit unit) { String result = null; if (declaration instanceof ClassOrInterface || declaration instanceof NothingType) { TypeDeclaration type = (TypeDeclaration) declaration; if (isLinkable(type)) { String typeUrl = getUrl(type, null); if (typeUrl != null) { result = buildLinkElement(typeUrl, getLinkText(type), "Go to " + type.getQualifiedNameString()); } } if( result == null ) { result = buildSpanElementWithNameAndTooltip(declaration); } } else if (declaration instanceof TypeParameter) { result = "<span class='type-parameter'>" + declaration.getName(unit) + "</span>"; } else if (declaration instanceof TypedDeclaration) { result = processTypedDeclaration((TypedDeclaration) declaration); } else if (declaration instanceof TypeAlias) { result = processTypeAlias((TypeAlias) declaration); } else { result = buildSpanElementWithNameAndTooltip(declaration); } return encodeResult(result); } @Override public boolean printAbbreviated() { return printAbbreviated; } @Override public boolean printTypeParameters() { return printTypeParameters; } @Override public boolean printTypeParameterDetail() { return printTypeParameterDetail; } @Override public boolean printQualifyingType() { return false; } }; public LinkRenderer(CeylonDocTool ceylonDocTool, Writer writer, Object from) { this.ceylonDocTool = ceylonDocTool; this.writer = writer; this.from = from; } public LinkRenderer(LinkRenderer linkRenderer) { this.to = linkRenderer.to; this.from = linkRenderer.from; this.ceylonDocTool = linkRenderer.ceylonDocTool; this.writer = linkRenderer.writer; this.customText = linkRenderer.customText; this.scope = linkRenderer.scope; this.anchor = linkRenderer.anchor; this.printAbbreviated = linkRenderer.printAbbreviated; this.printTypeParameters = linkRenderer.printTypeParameters; this.printTypeParameterDetail = linkRenderer.printTypeParameterDetail; this.printLinkDropdownMenu = linkRenderer.printLinkDropdownMenu; } public LinkRenderer to(Object to) { this.to = to; return this; } public LinkRenderer useCustomText(String customText) { this.customText = customText; return this; } public LinkRenderer withinText(boolean text) { withinText = text; return this; } public LinkRenderer useScope(Referenceable scope) { this.scope = scope; return this; } public LinkRenderer useAnchor(String anchor) { this.anchor = anchor; return this; } public LinkRenderer printAbbreviated(boolean printAbbreviated) { this.printAbbreviated = printAbbreviated; return this; } public LinkRenderer printTypeParameters(boolean printTypeParameters) { this.printTypeParameters = printTypeParameters; return this; } public LinkRenderer printTypeParameterDetail(boolean printTypeParameterDetail) { this.printTypeParameterDetail = printTypeParameterDetail; return this; } public LinkRenderer printWikiStyleLinks(boolean printWikiStyleLinks) { this.printWikiStyleLinks = printWikiStyleLinks; return this; } public LinkRenderer printLinkDropdownMenu(boolean printLinkDropdownMenu) { this.printLinkDropdownMenu = printLinkDropdownMenu; return this; } public LinkRenderer printParenthesisAfterMethodName(boolean printParenthesisAfterMethodName) { this.printParenthesisAfterMethodName = printParenthesisAfterMethodName; return this; } public LinkRenderer printMemberContainerName(boolean printMemberContainerName) { this.printMemberContainerName = printMemberContainerName; return this; } public String getLink() { String link = null; if (to instanceof String) { if (printWikiStyleLinks) { link = processWikiLink((String) to); } else { link = processAnnotationParam((String) to); } } else if (to instanceof Type) { link = processProducedType((Type) to); } else if (to instanceof Declaration) { link = processDeclaration(((Declaration) to)); } else if (to instanceof Module) { link = processModule((Module) to); } else if (to instanceof Package) { link = processPackage((Package) to); } return link; } public String getUrl() { return getUrl(to, anchor); } public String getResourceUrl(String to) throws IOException { return ceylonDocTool.getResourceUrl(from, to); } public String getSrcUrl(Object to) throws IOException { return ceylonDocTool.getSrcUrl(from, to); } public void write() throws IOException { writer.write(getLink()); } private String processModule(Module module) { String moduleUrl = getUrl(module, anchor); if (moduleUrl != null) { return buildLinkElement(moduleUrl, module.getNameAsString(), "Go to module"); } else { return module.getNameAsString(); } } private String processPackage(Package pkg) { String pkgUrl = getUrl(pkg, anchor); if (pkgUrl != null) { return buildLinkElement(pkgUrl, customText != null ? customText : pkg.getNameAsString(), "Go to package " + pkg.getNameAsString()); } else { return pkg.getNameAsString(); } } private String processDeclaration(Declaration decl) { if (decl instanceof TypeDeclaration) { return processProducedType(((TypeDeclaration) decl).getType()); } else { return processTypedDeclaration((TypedDeclaration) decl); } } private String processProducedType(Type producedType) { String result; boolean wasWithinText = withinText; withinText = false; try { result = producedTypeNamePrinter.print(producedType, null); } finally { withinText = wasWithinText; } result = decodeResult(result); if (withinText && customText==null) { result = "<code>" + result + "</code>"; } result = decorateWithLinkDropdownMenu(result, producedType); return result; } private String processTypedDeclaration(TypedDeclaration decl) { String declName = Util.getDeclarationName(decl); Scope declContainer = decl.getContainer(); if( isLinkable(decl) ) { String url = getUrl(declContainer, declName); if( url != null ) { return buildLinkElement(url, getLinkText(decl), "Go to " + decl.getQualifiedNameString()); } } String result = declName; if (withinText) { result = "<code>" + result + "</code>"; } if (customText != null) { result = customText; } return result; } private String processTypeAlias(TypeAlias alias) { String aliasName = alias.getName(); Scope aliasContainer = alias.getContainer(); if (isLinkable(alias)) { String url = getUrl(aliasContainer, aliasName); if (url != null) { return buildLinkElement(url, aliasName, "Go to " + alias.getQualifiedNameString()); } } return buildSpanElementWithNameAndTooltip(alias); } private String processWikiLink(final String docLinkText) { Tree.DocLink docLink = findDocLink(docLinkText, scope); if (docLink == null && scope instanceof Declaration) { Declaration refinedDeclaration = ((Declaration) scope).getRefinedDeclaration(); if (refinedDeclaration != scope) { docLink = findDocLink(docLinkText, refinedDeclaration); } } if (docLink != null) { if (docLink.getQualified() != null && docLink.getQualified().size() > 0) { return processDeclaration(docLink.getQualified().get(docLink.getQualified().size() - 1)); } else if (docLink.getBase() != null) { printAbbreviated = !isAbbreviatedType(docLink.getBase()); return processDeclaration(docLink.getBase()); } else if (docLink.getModule() != null) { return processModule(docLink.getModule()); } else if (docLink.getPkg() != null) { return processPackage(docLink.getPkg()); } } if (docLink != null && scope instanceof Annotated) { Annotation docAnnotation = getAnnotation(scope.getUnit(), ((Annotated) scope).getAnnotations(), "doc"); if (docAnnotation != null) { ceylonDocTool.warningBrokenLink(docLinkText, docLink, scope); } } return getUnresolvableLink(docLinkText); } private String processAnnotationParam(String text) { if( text.equals("module")) { Module mod = getCurrentModule(); if( mod != null) { return processModule(mod); } } if (text.startsWith("module ")) { String modName = text.substring(7); for (Module m : ceylonDocTool.getTypeChecker().getContext().getModules().getListOfModules()) { if (m.getNameAsString().equals(modName)) { return processModule(m); } } } if( text.equals("package")) { Package pkg = getCurrentPackage(); if (pkg != null) { return processPackage(pkg); } } if (text.startsWith("package ")) { String pkgName = text.substring(8); for (Module m : ceylonDocTool.getTypeChecker().getContext().getModules().getListOfModules()) { if (pkgName.startsWith(m.getNameAsString() + ".")) { Package pkg = m.getPackage(pkgName); if (pkg != null) { return processPackage(pkg); } } } } if( text.equals("interface") ) { Interface interf = getCurrentInterface(); if( interf != null ) { return processProducedType(interf.getType()); } } if( text.equals("class") ) { Class clazz = getCurrentClass(); if( clazz != null ) { return processProducedType(clazz.getType()); } } String declName; Scope currentScope; int pkgSeparatorIndex = text.indexOf("::"); if( pkgSeparatorIndex == -1 ) { declName = text; currentScope = resolveScope(scope); } else { String pkgName = text.substring(0, pkgSeparatorIndex); declName = text.substring(pkgSeparatorIndex+2, text.length()); currentScope = ceylonDocTool.getCurrentModule().getPackage(pkgName); } String[] declNames = declName.split("\\."); Declaration currentDecl = null; boolean isNested = false; for (String currentDeclName : declNames) { currentDecl = resolveDeclaration(currentScope, currentDeclName, isNested); if (currentDecl != null) { if( isValueWithTypeObject(currentDecl) ) { TypeDeclaration objectType = ((Value)currentDecl).getTypeDeclaration(); currentScope = objectType; currentDecl = objectType; } else { currentScope = resolveScope(currentDecl); } isNested = true; } else { break; } } // we can't link to parameters yet, unless they're toplevel if (currentDecl != null && !isParameter(currentDecl)) { if (currentDecl instanceof TypeDeclaration) { return processProducedType(((TypeDeclaration) currentDecl).getType()); } else { return processTypedDeclaration((TypedDeclaration) currentDecl); } } else { return getUnresolvableLink(text); } } private boolean isLinkable(Declaration decl) { if( decl == null ) { return false; } if( decl.isParameter() ) { return true; } if( !ceylonDocTool.isIncludeNonShared() ) { if( !decl.isShared() ) { return false; } Scope c = decl.getContainer(); while(c != null) { boolean isShared = true; if( c instanceof Declaration ) { isShared = ((Declaration) c).isShared(); } if( c instanceof Package ) { isShared = ((Package) c).isShared(); } if( !isShared ) { return false; } c = c.getContainer(); } } return true; } private boolean isValueWithTypeObject(Declaration decl) { if (Decl.isValue(decl)) { TypeDeclaration typeDeclaration = ((Value) decl).getTypeDeclaration(); if (typeDeclaration instanceof Class && typeDeclaration.isAnonymous()) { return true; } } return false; } private boolean isParameter(Declaration decl) { return decl instanceof FunctionOrValue && ((FunctionOrValue)decl).isParameter(); } private Declaration resolveDeclaration(Scope scope, String declName, boolean isNested) { Declaration decl = null; if (scope != null) { decl = scope.getMember(declName, null, false); if (decl == null && !isNested && scope instanceof Element) { decl = ((Element) scope).getUnit().getImportedDeclaration(declName, null, false); } if (decl == null && !isNested && !scope.getQualifiedNameString().equals(AbstractModelLoader.CEYLON_LANGUAGE) ) { decl = resolveDeclaration(scope.getContainer(), declName, isNested); } if (decl == null && declName.equals("Nothing") && scope.getQualifiedNameString().equals(AbstractModelLoader.CEYLON_LANGUAGE)) { decl = new NothingType(((Package) scope).getUnit()); } } else { Package pkg = ceylonDocTool.getCurrentModule().getPackage(AbstractModelLoader.CEYLON_LANGUAGE); if (pkg != null) { decl = resolveDeclaration(pkg, declName, isNested); } } return decl; } private Scope resolveScope(Referenceable referenceable) { if (referenceable instanceof Module) { return ((Module) referenceable).getPackage(referenceable.getNameAsString()); } else if (referenceable instanceof Scope) { return (Scope) referenceable; } else if (referenceable instanceof Declaration) { return ((Declaration) referenceable).getContainer(); } else { return null; } } private boolean isInCurrentModule(Object obj) { Module objModule = null; if (obj instanceof Module) { objModule = (Module) obj; } else if (obj instanceof Scope) { objModule = getPackage((Scope) obj).getModule(); } else if (obj instanceof Element) { objModule = getPackage(((Element) obj).getScope()).getModule(); } Module currentModule = ceylonDocTool.getCurrentModule(); if (currentModule != null && objModule != null) { return currentModule.equals(objModule); } return false; } private String getUnresolvableLink(final String docLinkText) { StringBuilder unresolvable = new StringBuilder(); unresolvable.append("<span class='link-unresolvable'>"); boolean hasCustomText = customText != null && !customText.equals(docLinkText); if (hasCustomText) { unresolvable.append(customText); unresolvable.append(" ("); } if (withinText) unresolvable.append("<code>"); int index = docLinkText.indexOf('|')+1; unresolvable.append(docLinkText.substring(index)); if (withinText) unresolvable.append("</code>"); if (hasCustomText) { unresolvable.append(")"); } unresolvable.append("</span>"); return unresolvable.toString(); } private String getLinkText(Declaration decl) { if (customText != null) { return customText; } else { String name = Util.getDeclarationName(decl); if( scope != null && scope.getUnit() != null ) { name = scope.getUnit().getAliasedName(decl, name); } String result; if (decl instanceof TypeDeclaration) { result = "<span class='type-identifier'>" + name + "</span>"; } else { if (decl instanceof Function && printParenthesisAfterMethodName) { name = name + "()"; } result = "<span class='identifier'>" + name + "</span>"; } if (printMemberContainerName && decl.isMember() && decl.getContainer() != from) { result = getLinkText((Declaration) decl.getContainer()) + '.' + result; } return result; } } private Package getPackage(Scope scope) { while (!(scope instanceof Package)) { scope = scope.getContainer(); } return (Package) scope; } private String getUrl(Object to, String anchor) { String url; List<Function> methods = new ArrayList<Function>(); while(to instanceof Function){ Function method = (Function) to; methods.add(method); to = method.getContainer(); } if (isInCurrentModule(to)) { url = getLocalUrl(to); } else { url = getExternalUrl(to); } if (url != null && anchor != null) { String sectionPackageAnchor = "#section-package"; if (url.endsWith(sectionPackageAnchor)) { url = url.substring(0, url.length() - sectionPackageAnchor.length()); } StringBuilder fragment = new StringBuilder(); if(!methods.isEmpty()) { Collections.reverse(methods); for(Function method : methods) { fragment.append(method.getName()); fragment.append("-"); } } fragment.append(anchor); url = url + "#" + fragment; } return url; } private String getLocalUrl(Object to) { try { return ceylonDocTool.getObjectUrl(from, to); } catch (IOException e) { throw new RuntimeException(e); } } private String getExternalUrl(Object to) { String url = null; if (to instanceof Module) { url = getExternalModuleUrl((Module)to); if (url != null) { url += "index.html"; } } else if (to instanceof Package) { Package pkg = (Package)to; url = getExternalModuleUrl(pkg.getModule()); if (url != null) { url += buildPackageUrlPath(pkg); url += "index.html"; } } else if (to instanceof ClassOrInterface) { ClassOrInterface klass = (ClassOrInterface) to; Package pkg = getPackage(klass); url = getExternalModuleUrl(pkg.getModule()); if (url != null) { url += buildPackageUrlPath(pkg); url += ceylonDocTool.getFileName(klass); } } return url; } private String getExternalModuleUrl(Module module) { if( ceylonDocTool.getLinks() != null ) { String moduleName = module.getNameAsString(); for (String link : ceylonDocTool.getLinks()) { String[] linkParts = divideToPatternAndUrl(link); String moduleNamePattern = linkParts[0]; String moduleRepoUrl = linkParts[1]; if (moduleNamePattern == null) { String moduleDocUrl = buildModuleUrl(moduleRepoUrl, module); if (isHttpProtocol(moduleDocUrl) && checkHttpUrlExist(moduleDocUrl)) { return moduleDocUrl; } if (isFileProtocol(moduleDocUrl) && checkFileUrlExist(moduleDocUrl)) { return moduleDocUrl; } } else if (moduleName.startsWith(moduleNamePattern)) { return buildModuleUrl(moduleRepoUrl, module); } } } return null; } private String buildLinkElement(String url, String text, String toolTip) { StringBuilder linkBuilder = new StringBuilder(); linkBuilder.append("<a "); if (customText != null) { linkBuilder.append("class='link-custom-text'"); } else { linkBuilder.append("class='link'"); } linkBuilder.append(" href='").append(url).append("'"); if (toolTip != null) { linkBuilder.append(" title='").append(toolTip).append("'"); } linkBuilder.append(">"); if (customText==null && withinText) { linkBuilder.append("<code>"); } linkBuilder.append(text); if (customText==null && withinText) { linkBuilder.append("</code>"); } linkBuilder.append("</a>"); return linkBuilder.toString(); } private String buildSpanElementWithNameAndTooltip(Declaration d) { StringBuilder spanBuilder = new StringBuilder(); spanBuilder.append("<span title='"); spanBuilder.append(d.getQualifiedNameString()); spanBuilder.append("'>"); if (withinText) spanBuilder.append("<code>"); spanBuilder.append(getLinkText(d)); if (withinText) spanBuilder.append("</code>"); spanBuilder.append("</span>"); return spanBuilder.toString(); } private String buildModuleUrl(String moduleRepoUrl, Module module) { StringBuilder moduleUrlBuilder = new StringBuilder(); moduleUrlBuilder.append(moduleRepoUrl); if (!moduleRepoUrl.endsWith("/")) { moduleUrlBuilder.append("/"); } moduleUrlBuilder.append(Util.join("/", module.getName())); moduleUrlBuilder.append("/"); moduleUrlBuilder.append(module.getVersion()); moduleUrlBuilder.append("/module-doc/api/"); return moduleUrlBuilder.toString(); } private String buildPackageUrlPath(Package pkg) { List<String> packagePath = pkg.getName().subList(pkg.getModule().getName().size(), pkg.getName().size()); if (!packagePath.isEmpty()) { return Util.join("/", packagePath) + "/"; } return ""; } public static String[] divideToPatternAndUrl(String link) { String moduleRepoUrl = null; String moduleNamePattern = null; int indexOfSeparator = link.indexOf("="); if (indexOfSeparator != -1) { moduleNamePattern = link.substring(0, indexOfSeparator); moduleRepoUrl = link.substring(indexOfSeparator + 1); } else { moduleRepoUrl = link; } return new String[] { moduleNamePattern, moduleRepoUrl }; } public static boolean isHttpProtocol(String url) { return url.startsWith("http://") || url.startsWith("https://"); } public static boolean isFileProtocol(String url) { return url.startsWith("file://"); } private boolean checkHttpUrlExist(String moduleUrl) { Boolean result = ceylonDocTool.getModuleUrlAvailabilityCache().get(moduleUrl); if( result == null ) { try { URL url = new URL(moduleUrl + "index.html"); HttpURLConnection con; Proxy proxy = DefaultToolOptions.getDefaultProxy(); if (proxy != null) { con = (HttpURLConnection) url.openConnection(proxy); } else { con = (HttpURLConnection) url.openConnection(); } con.setConnectTimeout((int) DefaultToolOptions.getDefaultTimeout()); con.setReadTimeout((int) DefaultToolOptions.getDefaultTimeout() * Constants.READ_TIMEOUT_MULTIPLIER); con.setRequestMethod("HEAD"); int responseCode = con.getResponseCode(); if( responseCode == HttpURLConnection.HTTP_OK ) { result = Boolean.TRUE; } else { ceylonDocTool.getLogger().warning(msg("info.urlDoesNotExist", moduleUrl)); result = Boolean.FALSE; } } catch (IOException e) { ceylonDocTool.getLogger().warning(msg("info.urlDoesNotExist", moduleUrl)); result = Boolean.FALSE; } ceylonDocTool.getModuleUrlAvailabilityCache().put(moduleUrl, result); } return result.booleanValue(); } private boolean checkFileUrlExist(String moduleUrl) { Boolean result = ceylonDocTool.getModuleUrlAvailabilityCache().get(moduleUrl); if( result == null ) { File moduleDocDir = new File(moduleUrl.substring("file://".length())); if (moduleDocDir.isDirectory() && moduleDocDir.exists()) { result = Boolean.TRUE; } else { ceylonDocTool.getLogger().warning(msg("info.urlDoesNotExist", moduleUrl)); result = Boolean.FALSE; } ceylonDocTool.getModuleUrlAvailabilityCache().put(moduleUrl, result); } return result.booleanValue(); } private static String encodeResult(String text) { if (text != null) { text = text.replaceAll("<", "#LT;"); text = text.replaceAll(">", "#GT;"); } return text; } private static String decodeResult(String text) { if (text != null) { text = text.replaceAll("&", "&amp;"); text = text.replaceAll("<", "&lt;"); text = text.replaceAll(">", "&gt;"); text = text.replaceAll("#LT;", "<"); text = text.replaceAll("#GT;", ">"); text = text.replaceAll("&lt;in ", "&lt;<span class='type-parameter-keyword'>in </span>"); text = text.replaceAll(",in ", ",<span class='type-parameter-keyword'>in </span>"); text = text.replaceAll("&lt;out ", "&lt;<span class='type-parameter-keyword'>out </span>"); text = text.replaceAll(",out ", ",<span class='type-parameter-keyword'>out </span>"); } return text; } private String decorateWithLinkDropdownMenu(String link, Type producedType) { if( !printLinkDropdownMenu || !printAbbreviated || !canLinkToCeylonLanguageModule() ) { return link; } List<Type> producedTypes = new ArrayList<Type>(); decompose(producedType, producedTypes); boolean containsOptional = false; boolean containsSequential = false; boolean containsSequence = false; boolean containsIterable = false; boolean containsEntry = false; boolean containsCallable = false; boolean containsTuple = false; for (Type pt : producedTypes) { if (abbreviateOptional(pt)) { containsOptional = true; } else if (abbreviateSequential(pt) && !link.contains("'Go to ceylon.language::Sequential'")) { containsSequential = true; } else if (abbreviateSequence(pt) && !link.contains("'Go to ceylon.language::Sequence'")) { containsSequence = true; } else if (abbreviateIterable(pt) && !link.contains("'Go to ceylon.language::Iterable'")) { containsIterable = true; } else if (abbreviateEntry(pt) && !link.contains("'Go to ceylon.language::Entry'")) { containsEntry = true; } else if (abbreviateCallable(pt) && !link.contains("'Go to ceylon.language::Callable'")) { containsCallable = true; } else if (abbreviateTuple(pt) && !link.contains("'Go to ceylon.language::Tuple'")) { containsTuple = true; } } Unit unit = producedType.getDeclaration().getUnit(); if( containsOptional || containsSequential || containsSequence || containsIterable || containsEntry || containsCallable || containsTuple ) { StringBuilder sb = new StringBuilder(); sb.append("<span class='link-dropdown'>"); sb.append(link.replaceAll("class='link'", "class='link type-identifier'")); sb.append("<span class='dropdown'>"); sb.append("<a class='dropdown-toggle' data-toggle='dropdown' href='#'><b title='Show more links' class='caret'></b></a>"); sb.append("<ul class='dropdown-menu'>"); if( containsOptional ) { sb.append(getLinkMenuItem(unit.getNullDeclaration(), "abbreviations X? means Null|X")); } if( containsSequential ) { sb.append(getLinkMenuItem(unit.getSequentialDeclaration(), "abbreviation X[] or [X*] means Sequential&lt;X&gt;")); } if( containsSequence ) { sb.append(getLinkMenuItem(unit.getSequenceDeclaration(), "abbreviation [X+] means Sequence&lt;X&gt;")); } if( containsIterable ) { sb.append(getLinkMenuItem(unit.getIterableDeclaration(), "abbreviation {X+} or {X*} means Iterable&lt;X,Nothing&gt; or Iterable&lt;X,Null&gt;")); } if( containsEntry ) { sb.append(getLinkMenuItem(unit.getEntryDeclaration(), "abbreviation X-&gt;Y means Entry&lt;X,Y&gt;")); } if( containsCallable ) { sb.append(getLinkMenuItem(unit.getCallableDeclaration(), "abbreviation X(Y,Z) means Callable&lt;X,[Y,Z]&gt;")); } if( containsTuple ) { sb.append(getLinkMenuItem(unit.getTupleDeclaration(), "abbreviation [X,Y] means Tuple&lt;X|Y,X,Tuple&lt;Y,Y,[]&gt;&gt;")); } sb.append("</ul>"); // dropdown-menu sb.append("</span>"); // dropdown sb.append("</span>"); // link-dropdown return sb.toString(); } return link; } private boolean canLinkToCeylonLanguageModule() { Module currentModule = ceylonDocTool.getCurrentModule(); if (currentModule.isLanguageModule()) { return true; } else { Module languageModule = currentModule.getLanguageModule(); String languageModuleUrl = getExternalModuleUrl(languageModule); return languageModuleUrl != null; } } private void decompose(Type pt, List<Type> producedTypes) { if (!producedTypes.contains(pt)) { producedTypes.add(pt); if (pt.isIntersection()) { for (Type satisfiedType : pt.getSatisfiedTypes()) { decompose(satisfiedType, producedTypes); } } else if (pt.isUnion()) { for (Type caseType : pt.getCaseTypes()) { decompose(caseType, producedTypes); } } if (!pt.getTypeArgumentList().isEmpty()) { for (Type typeArgument : pt.getTypeArgumentList()) { decompose(typeArgument, producedTypes); } } } } private String getLinkMenuItem(Declaration decl, String description) { String url = new LinkRenderer(this). to(decl). useCustomText(""). printLinkDropdownMenu(false). printAbbreviated(false). printTypeParameters(false). getUrl(); StringBuilder sb = new StringBuilder(); sb.append("<li>"); sb.append("<a class='link' href='").append(url).append("'>"); sb.append("Go to ").append(decl.getName()).append(" "); sb.append("<small>").append(description).append("</small>"); sb.append("</a>"); sb.append("</li>"); return sb.toString(); } private Tree.DocLink findDocLink(final String docLinkText, Referenceable referenceable) { final Tree.DocLink[] docLinks = new Tree.DocLink[1]; Node scopeNode = ceylonDocTool.getNode(referenceable); if (scopeNode != null) { scopeNode.visit(new Visitor() { @Override public void visit(Tree.DocLink docLink) { String s1 = normalizeSpaces(docLinkText); String s2 = normalizeSpaces(docLink.getText()); if (s1.equals(s2)) { docLinks[0] = docLink; return; } } }); } return docLinks[0]; } private Module getCurrentModule() { if (scope instanceof Module) { return (Module) scope; } else if (scope instanceof Package) { return ((Package) scope).getModule(); } else if (scope instanceof Declaration) { return scope.getUnit().getPackage().getModule(); } return null; } private Package getCurrentPackage() { if (scope instanceof Module) { return ((Module) scope).getRootPackage(); } else if (scope instanceof Package) { return (Package) scope; } else if (scope instanceof Declaration) { return scope.getUnit().getPackage(); } return null; } private Interface getCurrentInterface() { Object o = scope; while (o != null) { if (o instanceof Interface) { return (Interface) o; } else if (o instanceof Declaration) { o = ((Declaration) o).getContainer(); } else { o = null; } } return null; } private Class getCurrentClass() { Object o = scope; while (o != null) { if (o instanceof Class) { return (Class) o; } else if (o instanceof Declaration) { o = ((Declaration) o).getContainer(); } else { o = null; } } return null; } }
apache-2.0
wardev/orekit
src/test/java/org/orekit/propagation/SpacecraftStateTest.java
25959
/* Copyright 2002-2014 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.propagation; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.orekit.Utils; import org.orekit.attitudes.Attitude; import org.orekit.attitudes.AttitudeProvider; import org.orekit.attitudes.BodyCenterPointing; import org.orekit.errors.OrekitException; import org.orekit.errors.OrekitMessages; import org.orekit.frames.FramesFactory; import org.orekit.frames.Transform; import org.orekit.orbits.CartesianOrbit; import org.orekit.orbits.KeplerianOrbit; import org.orekit.orbits.Orbit; import org.orekit.orbits.PositionAngle; import org.orekit.propagation.analytical.EcksteinHechlerPropagator; import org.orekit.time.AbsoluteDate; import org.orekit.time.DateComponents; import org.orekit.time.TimeComponents; import org.orekit.time.TimeScalesFactory; import org.orekit.utils.IERSConventions; import org.orekit.utils.PVCoordinates; import org.orekit.utils.TimeStampedPVCoordinates; public class SpacecraftStateTest { @Test public void testAcceleration() throws OrekitException { //setup PVCoordinates pva = new PVCoordinates( orbit.getPVCoordinates().getPosition(), orbit.getPVCoordinates().getVelocity(), new Vector3D(1,2,3)); Attitude attitude = attitudeLaw.getAttitude(orbit, orbit.getDate(), orbit.getFrame()); //action SpacecraftState state = new SpacecraftState(orbit, pva, attitude, mass); //verify Assert.assertEquals(orbit, state.getOrbit()); TimeStampedPVCoordinates actualPva = state.getPVCoordinates(); Assert.assertEquals(pva.getPosition(), actualPva.getPosition()); Assert.assertEquals(pva.getVelocity(), actualPva.getVelocity()); Assert.assertEquals(pva.getAcceleration(), actualPva.getAcceleration()); actualPva = state.getPVCoordinates(state.getFrame()); Assert.assertEquals(pva.getPosition(), actualPva.getPosition()); Assert.assertEquals(pva.getVelocity(), actualPva.getVelocity()); Assert.assertEquals(pva.getAcceleration(), actualPva.getAcceleration()); } @Test public void testShiftError() throws ParseException, OrekitException { // polynomial models for interpolation error in position, velocity, acceleration and attitude // these models grow as follows // interpolation time (s) position error (m) velocity error (m/s) acceleration error (m/s²) attitude error (°) // 60 30 1 0.014 0.00002 // 120 100 2 0.013 0.00009 // 300 600 4 0.011 0.0009 // 600 2000 6 0.006 0.006 // 900 4000 6 0.002 0.02 // the expected maximum residuals with respect to these models are about 0.2m, 0.8mm/s, 7.9μm/s² and 2.8e-7° PolynomialFunction pModel = new PolynomialFunction(new double[] { -0.16513714130703838, 0.008052836586593358, 0.007306374155052651, -1.9942719771217313E-6, -1.8063354449344768E-9, 9.042229494006868E-13, }); PolynomialFunction vModel = new PolynomialFunction(new double[] { -6.205041765231733E-4, 0.014820651821078279, -7.458097665912488E-6, -1.5914983761563204E-9, -1.7936013181449342E-12, 2.187916095307246E-15, }); PolynomialFunction aModel = new PolynomialFunction(new double[] { 0.014788789776214587, -1.418490913753379E-5, 1.947898940800356E-9, 2.6179181901457335E-12, -7.603278343088821E-15, 2.968153861123117E-18, }); PolynomialFunction rModel = new PolynomialFunction(new double[] { -2.7689062182403017E-6, 1.7406542555507358E-7, 2.510979532481025E-9, 2.039932266627844E-11, 9.912634888010535E-15, -3.5015638902258456E-18, }); AbsoluteDate centerDate = orbit.getDate().shiftedBy(100.0); SpacecraftState centerState = propagator.propagate(centerDate); double maxResidualP = 0; double maxResidualV = 0; double maxResidualA = 0; double maxResidualR = 0; for (double dt = 0; dt < 900.0; dt += 5) { SpacecraftState shifted = centerState.shiftedBy(dt); SpacecraftState propagated = propagator.propagate(centerDate.shiftedBy(dt)); PVCoordinates dpv = new PVCoordinates(propagated.getPVCoordinates(), shifted.getPVCoordinates()); double residualP = pModel.value(dt) - dpv.getPosition().getNorm(); double residualV = vModel.value(dt) - dpv.getVelocity().getNorm(); double residualA = aModel.value(dt) - dpv.getAcceleration().getNorm(); double residualR = rModel.value(dt) - FastMath.toDegrees(Rotation.distance(shifted.getAttitude().getRotation(), propagated.getAttitude().getRotation())); maxResidualP = FastMath.max(maxResidualP, FastMath.abs(residualP)); maxResidualV = FastMath.max(maxResidualV, FastMath.abs(residualV)); maxResidualA = FastMath.max(maxResidualA, FastMath.abs(residualA)); maxResidualR = FastMath.max(maxResidualR, FastMath.abs(residualR)); } Assert.assertEquals(0.2, maxResidualP, 0.1); Assert.assertEquals(0.0008, maxResidualV, 0.0001); Assert.assertEquals(7.9e-6, maxResidualA, 1.0e-7); Assert.assertEquals(2.8e-6, maxResidualR, 1.0e-1); } @Test public void testInterpolation() throws ParseException, OrekitException { checkInterpolationError( 2, 106.46533, 0.40709287, 169847806.33e-9, 0.0, 450 * 450); checkInterpolationError( 3, 0.00353, 0.00003250, 189886.01e-9, 0.0, 0.0); checkInterpolationError( 4, 0.00002, 0.00000023, 232.25e-9, 0.0, 0.0); } private void checkInterpolationError(int n, double expectedErrorP, double expectedErrorV, double expectedErrorA, double expectedErrorM, double expectedErrorQ) throws OrekitException { AbsoluteDate centerDate = orbit.getDate().shiftedBy(100.0); SpacecraftState centerState = propagator.propagate(centerDate).addAdditionalState("quadratic", 0); List<SpacecraftState> sample = new ArrayList<SpacecraftState>(); for (int i = 0; i < n; ++i) { double dt = i * 900.0 / (n - 1); SpacecraftState state = propagator.propagate(centerDate.shiftedBy(dt)); state = state.addAdditionalState("quadratic", dt * dt); sample.add(state); } double maxErrorP = 0; double maxErrorV = 0; double maxErrorA = 0; double maxErrorM = 0; double maxErrorQ = 0; for (double dt = 0; dt < 900.0; dt += 5) { SpacecraftState interpolated = centerState.interpolate(centerDate.shiftedBy(dt), sample); SpacecraftState propagated = propagator.propagate(centerDate.shiftedBy(dt)); PVCoordinates dpv = new PVCoordinates(propagated.getPVCoordinates(), interpolated.getPVCoordinates()); maxErrorP = FastMath.max(maxErrorP, dpv.getPosition().getNorm()); maxErrorV = FastMath.max(maxErrorV, dpv.getVelocity().getNorm()); maxErrorA = FastMath.max(maxErrorA, FastMath.toDegrees(Rotation.distance(interpolated.getAttitude().getRotation(), propagated.getAttitude().getRotation()))); maxErrorM = FastMath.max(maxErrorM, FastMath.abs(interpolated.getMass() - propagated.getMass())); maxErrorQ = FastMath.max(maxErrorQ, FastMath.abs(interpolated.getAdditionalState("quadratic")[0] - dt * dt)); } Assert.assertEquals(expectedErrorP, maxErrorP, 1.0e-3); Assert.assertEquals(expectedErrorV, maxErrorV, 1.0e-6); Assert.assertEquals(expectedErrorA, maxErrorA, 4.0e-10); Assert.assertEquals(expectedErrorM, maxErrorM, 1.0e-15); Assert.assertEquals(expectedErrorQ, maxErrorQ, 2.0e-10); } // copied from CartesianParametersTest and modified to interpolate SpacraftState. @Test public void testInterpolation2() throws OrekitException { final double ehMu = 3.9860047e14; final double ae = 6.378137e6; final double c20 = -1.08263e-3; final double c30 = 2.54e-6; final double c40 = 1.62e-6; final double c50 = 2.3e-7; final double c60 = -5.5e-7; final AbsoluteDate date = AbsoluteDate.J2000_EPOCH.shiftedBy(584.); final Vector3D position = new Vector3D(3220103., 69623., 6449822.); final Vector3D velocity = new Vector3D(6414.7, -2006., -3180.); final CartesianOrbit initialOrbit = new CartesianOrbit(new PVCoordinates(position, velocity), FramesFactory.getEME2000(), date, ehMu); EcksteinHechlerPropagator propagator = new EcksteinHechlerPropagator(initialOrbit, ae, ehMu, c20, c30, c40, c50, c60); // set up a 5 points sample List<SpacecraftState> sample = new ArrayList<SpacecraftState>(); for (double dt = 0; dt < 251.0; dt += 60.0) { sample.add(propagator.propagate(date.shiftedBy(dt))); } // well inside the sample, interpolation should be much better than Keplerian shift // this is bacause we take the full non-Keplerian acceleration into account in // the Cartesian parameters, which in this case is preserved by the // Eckstein-Hechler propagator double maxShiftPError = 0; double maxInterpolationPError = 0; double maxShiftVError = 0; double maxInterpolationVError = 0; for (double dt = 0; dt < 240.0; dt += 1.0) { AbsoluteDate t = initialOrbit.getDate().shiftedBy(dt); PVCoordinates propagated = propagator.propagate(t).getPVCoordinates(); PVCoordinates shiftError = new PVCoordinates(propagated, initialOrbit.shiftedBy(dt).getPVCoordinates()); PVCoordinates interpolationError = new PVCoordinates(propagated, sample.get(0).interpolate(t, sample).getPVCoordinates()); maxShiftPError = FastMath.max(maxShiftPError, shiftError.getPosition().getNorm()); maxInterpolationPError = FastMath.max(maxInterpolationPError, interpolationError.getPosition().getNorm()); maxShiftVError = FastMath.max(maxShiftVError, shiftError.getVelocity().getNorm()); maxInterpolationVError = FastMath.max(maxInterpolationVError, interpolationError.getVelocity().getNorm()); } Assert.assertTrue(maxShiftPError > 390.0); Assert.assertTrue(maxInterpolationPError < 3.0e-8); Assert.assertTrue(maxShiftVError > 3.0); Assert.assertTrue(maxInterpolationVError < 2.0e-9); // if we go far past sample end, interpolation becomes worse than Keplerian shift maxShiftPError = 0; maxInterpolationPError = 0; maxShiftVError = 0; maxInterpolationVError = 0; for (double dt = 500.0; dt < 650.0; dt += 1.0) { AbsoluteDate t = initialOrbit.getDate().shiftedBy(dt); PVCoordinates propagated = propagator.propagate(t).getPVCoordinates(); PVCoordinates shiftError = new PVCoordinates(propagated, initialOrbit.shiftedBy(dt).getPVCoordinates()); PVCoordinates interpolationError = new PVCoordinates(propagated, sample.get(0).interpolate(t, sample).getPVCoordinates()); maxShiftPError = FastMath.max(maxShiftPError, shiftError.getPosition().getNorm()); maxInterpolationPError = FastMath.max(maxInterpolationPError, interpolationError.getPosition().getNorm()); maxShiftVError = FastMath.max(maxShiftVError, shiftError.getVelocity().getNorm()); maxInterpolationVError = FastMath.max(maxInterpolationVError, interpolationError.getVelocity().getNorm()); } Assert.assertTrue(maxShiftPError < 2500.0); Assert.assertTrue(maxInterpolationPError > 6000.0); Assert.assertTrue(maxShiftVError < 7.0); Assert.assertTrue(maxInterpolationVError > 170.0); } @Test(expected=IllegalArgumentException.class) public void testDatesConsistency() throws OrekitException { new SpacecraftState(orbit, attitudeLaw.getAttitude(orbit.shiftedBy(10.0), orbit.getDate().shiftedBy(10.0), orbit.getFrame())); } /** * Check orbit and attitude dates can be off by a few ulps. I see this when using * FixedRate attitude provider. */ @Test public void testDateConsistencyClose() throws OrekitException { //setup Orbit orbit10Shifts = orbit; for (int i = 0; i < 10; i++) { orbit10Shifts = orbit10Shifts.shiftedBy(0.1); } final Orbit orbit1Shift = orbit.shiftedBy(1); Attitude shiftedAttitude = attitudeLaw .getAttitude(orbit1Shift, orbit1Shift.getDate(), orbit.getFrame()); //verify dates are very close, but not equal Assert.assertNotEquals(shiftedAttitude.getDate(), orbit10Shifts.getDate()); Assert.assertEquals( shiftedAttitude.getDate().durationFrom(orbit10Shifts.getDate()), 0, Precision.EPSILON); //action + verify no exception is thrown new SpacecraftState(orbit10Shifts, shiftedAttitude); } @Test(expected=IllegalArgumentException.class) public void testFramesConsistency() throws OrekitException { new SpacecraftState(orbit, new Attitude(orbit.getDate(), FramesFactory.getGCRF(), Rotation.IDENTITY, Vector3D.ZERO, Vector3D.ZERO)); } @Test public void testTransform() throws ParseException, OrekitException { double maxDP = 0; double maxDV = 0; double maxDA = 0; for (double t = 0; t < orbit.getKeplerianPeriod(); t += 60) { final SpacecraftState state = propagator.propagate(orbit.getDate().shiftedBy(t)); final Transform transform = state.toTransform().getInverse(); PVCoordinates pv = transform.transformPVCoordinates(PVCoordinates.ZERO); PVCoordinates dPV = new PVCoordinates(pv, state.getPVCoordinates()); Vector3D mZDirection = transform.transformVector(Vector3D.MINUS_K); double alpha = Vector3D.angle(mZDirection, state.getPVCoordinates().getPosition()); maxDP = FastMath.max(maxDP, dPV.getPosition().getNorm()); maxDV = FastMath.max(maxDV, dPV.getVelocity().getNorm()); maxDA = FastMath.max(maxDA, FastMath.toDegrees(alpha)); } Assert.assertEquals(0.0, maxDP, 1.0e-6); Assert.assertEquals(0.0, maxDV, 1.0e-9); Assert.assertEquals(0.0, maxDA, 1.0e-12); } @Test public void testAdditionalStates() throws OrekitException { final SpacecraftState state = propagator.propagate(orbit.getDate().shiftedBy(60)); final SpacecraftState extended = state. addAdditionalState("test-1", new double[] { 1.0, 2.0 }). addAdditionalState("test-2", 42.0); Assert.assertEquals(0, state.getAdditionalStates().size()); Assert.assertFalse(state.hasAdditionalState("test-1")); try { state.getAdditionalState("test-1"); Assert.fail("an exception should have been thrown"); } catch (OrekitException oe) { Assert.assertEquals(oe.getSpecifier(), OrekitMessages.UNKNOWN_ADDITIONAL_STATE); Assert.assertEquals(oe.getParts()[0], "test-1"); } try { state.ensureCompatibleAdditionalStates(extended); Assert.fail("an exception should have been thrown"); } catch (OrekitException oe) { Assert.assertEquals(oe.getSpecifier(), OrekitMessages.UNKNOWN_ADDITIONAL_STATE); Assert.assertTrue(oe.getParts()[0].toString().startsWith("test-")); } try { extended.ensureCompatibleAdditionalStates(state); Assert.fail("an exception should have been thrown"); } catch (OrekitException oe) { Assert.assertEquals(oe.getSpecifier(), OrekitMessages.UNKNOWN_ADDITIONAL_STATE); Assert.assertTrue(oe.getParts()[0].toString().startsWith("test-")); } try { extended.ensureCompatibleAdditionalStates(extended.addAdditionalState("test-2", new double[7])); Assert.fail("an exception should have been thrown"); } catch (DimensionMismatchException dme) { Assert.assertEquals(dme.getArgument(), 7); } Assert.assertEquals(2, extended.getAdditionalStates().size()); Assert.assertTrue(extended.hasAdditionalState("test-1")); Assert.assertTrue(extended.hasAdditionalState("test-2")); Assert.assertEquals( 1.0, extended.getAdditionalState("test-1")[0], 1.0e-15); Assert.assertEquals( 2.0, extended.getAdditionalState("test-1")[1], 1.0e-15); Assert.assertEquals(42.0, extended.getAdditionalState("test-2")[0], 1.0e-15); // test various constructors Map<String, double[]> map = new HashMap<String, double[]>(); map.put("test-3", new double[] { -6.0 }); SpacecraftState sO = new SpacecraftState(state.getOrbit(), map); Assert.assertEquals(-6.0, sO.getAdditionalState("test-3")[0], 1.0e-15); SpacecraftState sOA = new SpacecraftState(state.getOrbit(), state.getAttitude(), map); Assert.assertEquals(-6.0, sOA.getAdditionalState("test-3")[0], 1.0e-15); SpacecraftState sOM = new SpacecraftState(state.getOrbit(), state.getMass(), map); Assert.assertEquals(-6.0, sOM.getAdditionalState("test-3")[0], 1.0e-15); SpacecraftState sOAM = new SpacecraftState(state.getOrbit(), state.getAttitude(), state.getMass(), map); Assert.assertEquals(-6.0, sOAM.getAdditionalState("test-3")[0], 1.0e-15); } @Test public void testSerialization() throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, OrekitException { propagator.resetInitialState(propagator.getInitialState(). addAdditionalState("p1", 12.25). addAdditionalState("p2", 1, 2, 3)); SpacecraftState state = propagator.propagate(orbit.getDate().shiftedBy(123.456)); Assert.assertEquals(2, state.getAdditionalStates().size()); Assert.assertEquals(1, state.getAdditionalState("p1").length); Assert.assertEquals(12.25, state.getAdditionalState("p1")[0], 1.0e-15); Assert.assertEquals(3, state.getAdditionalState("p2").length); Assert.assertEquals(1.0, state.getAdditionalState("p2")[0], 1.0e-15); Assert.assertEquals(2.0, state.getAdditionalState("p2")[1], 1.0e-15); Assert.assertEquals(3.0, state.getAdditionalState("p2")[2], 1.0e-15); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(state); Assert.assertTrue(bos.size() > 700); Assert.assertTrue(bos.size() < 800); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); SpacecraftState deserialized = (SpacecraftState) ois.readObject(); Assert.assertEquals(0.0, Vector3D.distance(state.getPVCoordinates().getPosition(), deserialized.getPVCoordinates().getPosition()), 1.0e-10); Assert.assertEquals(0.0, Vector3D.distance(state.getPVCoordinates().getVelocity(), deserialized.getPVCoordinates().getVelocity()), 1.0e-10); Assert.assertEquals(0.0, Rotation.distance(state.getAttitude().getRotation(), deserialized.getAttitude().getRotation()), 1.0e-10); Assert.assertEquals(0.0, Vector3D.distance(state.getAttitude().getSpin(), deserialized.getAttitude().getSpin()), 1.0e-10); Assert.assertEquals(state.getDate(), deserialized.getDate()); Assert.assertEquals(state.getMu(), deserialized.getMu(), 1.0e-10); Assert.assertEquals(state.getFrame().getName(), deserialized.getFrame().getName()); Assert.assertEquals(2, deserialized.getAdditionalStates().size()); Assert.assertEquals(1, deserialized.getAdditionalState("p1").length); Assert.assertEquals(12.25, deserialized.getAdditionalState("p1")[0], 1.0e-15); Assert.assertEquals(3, deserialized.getAdditionalState("p2").length); Assert.assertEquals(1.0, deserialized.getAdditionalState("p2")[0], 1.0e-15); Assert.assertEquals(2.0, deserialized.getAdditionalState("p2")[1], 1.0e-15); Assert.assertEquals(3.0, deserialized.getAdditionalState("p2")[2], 1.0e-15); } @Before public void setUp() { try { Utils.setDataRoot("regular-data"); double mu = 3.9860047e14; double ae = 6.378137e6; double c20 = -1.08263e-3; double c30 = 2.54e-6; double c40 = 1.62e-6; double c50 = 2.3e-7; double c60 = -5.5e-7; mass = 2500; double a = 7187990.1979844316; double e = 0.5e-4; double i = 1.7105407051081795; double omega = 1.9674147913622104; double OMEGA = FastMath.toRadians(261); double lv = 0; AbsoluteDate date = new AbsoluteDate(new DateComponents(2004, 01, 01), TimeComponents.H00, TimeScalesFactory.getUTC()); orbit = new KeplerianOrbit(a, e, i, omega, OMEGA, lv, PositionAngle.TRUE, FramesFactory.getEME2000(), date, mu); attitudeLaw = new BodyCenterPointing(FramesFactory.getITRF(IERSConventions.IERS_2010, true)); propagator = new EcksteinHechlerPropagator(orbit, attitudeLaw, mass, ae, mu, c20, c30, c40, c50, c60); } catch (OrekitException oe) { Assert.fail(oe.getLocalizedMessage()); } } @After public void tearDown() { mass = Double.NaN; orbit = null; attitudeLaw = null; propagator = null; } private double mass; private Orbit orbit; private AttitudeProvider attitudeLaw; private Propagator propagator; }
apache-2.0
tubav/fiteagle2
boundary/src/main/java/org/fiteagle/boundary/MessageBusApplicationServerFactory.java
1344
package org.fiteagle.boundary; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Session; import javax.naming.InitialContext; import javax.naming.NamingException; public class MessageBusApplicationServerFactory { public static final String DESTINATION_DEFAULT = "java:/topic/fiteagle"; public static final String CONNECTION_FACTORY_LOCAL = "java:/ConnectionFactory"; private static final String username = "fiteagle"; private static final String password = "fiteagle"; public static MessageBus createMessageBus() throws NamingException, JMSException { final InitialContext mycontext = new InitialContext(); final ConnectionFactory myfactory = (ConnectionFactory) mycontext .lookup(MessageBusApplicationServerFactory.CONNECTION_FACTORY_LOCAL); final Destination mydestination = (Destination) mycontext .lookup(MessageBusApplicationServerFactory.DESTINATION_DEFAULT); final Connection myconnection = myfactory.createConnection( MessageBusApplicationServerFactory.username, MessageBusApplicationServerFactory.password); final Session mysession = myconnection.createSession(false, Session.AUTO_ACKNOWLEDGE); myconnection.start(); return new MessageBus(myfactory, myconnection, mysession, mydestination); } }
apache-2.0
phac-nml/irida
src/test/java/ca/corefacility/bioinformatics/irida/validators/ValidateMethodParametersAspectTest.java
4460
package ca.corefacility.bioinformatics.irida.validators; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import javax.validation.Validator; import org.hibernate.validator.internal.engine.ConstraintViolationImpl; import org.hibernate.validator.internal.engine.path.PathImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.aspectj.annotation.AspectJProxyFactory; import com.google.common.collect.Lists; /** * Unit tests for validating method parameters. */ public class ValidateMethodParametersAspectTest { private ValidMethodParametersAspect aspect; private AnnotatedMethodsClass proxy; private AnnotatedInterface interfaceProxy; @Mock private Validator validator; @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); AnnotatedMethodsClass target = new AnnotatedMethodsClass(); AnnotatedInterfaceImpl interfaceProxyTarget = new AnnotatedInterfaceImpl(); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(target); AspectJProxyFactory interfaceProxyFactory = new AspectJProxyFactory(interfaceProxyTarget); aspect = new ValidMethodParametersAspect(validator); proxyFactory.addAspect(aspect); interfaceProxyFactory.addAspect(aspect); proxy = proxyFactory.getProxy(); interfaceProxy = interfaceProxyFactory.getProxy(); } @Test public void testOneMethodParameterAnnotated() { String validated = "this should be validated"; proxy.testOneValidParameter(validated); verify(validator).validate(validated); } @Test public void testManyMethodParameterAnnotated() { String first = "first"; String second = "second"; String third = "third"; String fourth = "fourth"; proxy.testManyValidParameters(first, second, third, fourth); verify(validator, times(1)).validate(first); verify(validator, times(1)).validate(second); verify(validator, times(0)).validate(third); verify(validator, times(1)).validate(fourth); } @Test public void testThrowsConstraintViolations() { String first = "first"; Set<ConstraintViolation<Object>> violations = new HashSet<>(); violations.add(ConstraintViolationImpl.forBeanValidation(null, null, null, null, Object.class, null, null, first, PathImpl.createRootPath(), null, null)); when(validator.validate(any())).thenReturn(violations); assertThrows(ConstraintViolationException.class, () -> { proxy.testOneValidParameter(first); }); } @Test public void testExecutesAnnotatedInterface() { String param = "Paramter"; interfaceProxy.testParameter(param); verify(validator).validate(param); } @Test public void testExecutesArgAnnotatedInImpl() { String param = "Parameter"; interfaceProxy.testParameterAnnotatedInClass(param); verify(validator).validate(param); } @Test public void testValidatesIterable() { List<String> collection = Lists.newArrayList("first", "second", "third", "fourth"); interfaceProxy.testIterableValidAnnotation(collection); verify(validator, times(collection.size())).validate(any(String.class)); for (String el : collection) { verify(validator).validate(el); } } private static class AnnotatedMethodsClass { public AnnotatedMethodsClass() { } public void testOneValidParameter(@Valid String param) { } public void testManyValidParameters(@Valid String first, @Valid String second, String third, @Valid String fourth) { } } private static interface AnnotatedInterface { public void testParameter(@Valid String parameter); public void testParameterAnnotatedInClass(String parameter); public void testIterableValidAnnotation(@Valid Iterable<String> collection); } private static class AnnotatedInterfaceImpl implements AnnotatedInterface { public AnnotatedInterfaceImpl() { } @Override public void testParameter(String parameter) { } @Override public void testParameterAnnotatedInClass(@Valid String parameter) { } @Override public void testIterableValidAnnotation(Iterable<String> collection) { } } }
apache-2.0
vamshikk/javapractice
JavaProblems/LongestPalindromicSubstring/src/com/vk/palindrome/soln2/LongestPalindromicSubstringSoln2.java
1329
package com.vk.palindrome.soln2; // O(N^2) time with only O(1) space public class LongestPalindromicSubstringSoln2 { public static void main(String[] args) { char[] str = "geelakeyyekalleeg".toCharArray(); // char[] str = "aaawwwwaaa".toCharArray(); System.out.println("The longest palindrome length is " + longestPalindromicSubstr_Soln1(str)); } public static int longestPalindromicSubstr_Soln1(char[] str) { int sLen = str.length; if(sLen == 0) return 0; int[] iLongest = { 0, 1 }; for(int i = 0; i < sLen - 1; i++) { int[] p1Range = searchPalinArndCenter(str, i, i); if((p1Range[1] - p1Range[0]) > (iLongest[1] - iLongest[0])) iLongest = p1Range; int[] p2Range = searchPalinArndCenter(str, i, i + 1); if((p2Range[1] - p2Range[0]) > (iLongest[1] - iLongest[0])) iLongest = p2Range; } System.out.print("The longest palindrome is "); for(int i = iLongest[0]; i <= iLongest[1]; i++) { System.out.print(str[i]); } System.out.println(); return (iLongest[1] - iLongest[0] + 1); } public static int[] searchPalinArndCenter(char[] str, int i1, int i2) { int l = i1; int r = i2; int len = str.length; while(l >= 0 && r <= len - 1 && str[l] == str[r]) { l--; r++; } int[] retRange = { l + 1, r - 1 }; return retRange; } }
apache-2.0
thpeng/spring-time
spring-time-helloworld/src/main/java/ch/thp/proto/spring/time/hello/domain/HelloWorld.java
1614
/* * Copyright 2014 thpeng. * * 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 ch.thp.proto.spring.time.hello.domain; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.hibernate.annotations.Type; /** * simple entity with a database generated id, a string and a date. * @author thierry */ @Data @NoArgsConstructor() @RequiredArgsConstructor @Entity @Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"aName"},name = "unique_aname")}) public class HelloWorld { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @NonNull private String aName; @NonNull @Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentLocalDate") private LocalDate aBirthDay; }
apache-2.0
mtagle/kafka-connect-bigquery
kcbq-connector/src/main/java/com/wepay/kafka/connect/bigquery/retrieve/IdentitySchemaRetriever.java
1387
/* * Copyright 2020 Confluent, Inc. * * This software contains code derived from the WePay BigQuery Kafka Connector, Copyright WePay, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.wepay.kafka.connect.bigquery.retrieve; import com.wepay.kafka.connect.bigquery.api.SchemaRetriever; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.sink.SinkRecord; import java.util.Map; /** * Fetches the key Schema and value Schema from a Sink Record */ public class IdentitySchemaRetriever implements SchemaRetriever { @Override public void configure(Map<String, String> properties) { } @Override public Schema retrieveKeySchema(SinkRecord record) { return record.keySchema(); } @Override public Schema retrieveValueSchema(SinkRecord record) { return record.valueSchema(); } }
apache-2.0
planoAccess/clonedONOS
drivers/src/main/java/org/onosproject/driver/pipeline/CpqdOFDPA2Pipeline.java
20778
/* * Copyright 2015 Open Networking Laboratory * * 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.driver.pipeline; import static org.slf4j.LoggerFactory.getLogger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.onlab.packet.Ethernet; import org.onlab.packet.VlanId; import org.onosproject.core.ApplicationId; import org.onosproject.net.Port; import org.onosproject.net.PortNumber; import org.onosproject.net.behaviour.NextGroup; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleOperations; import org.onosproject.net.flow.FlowRuleOperationsContext; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.flow.criteria.Criteria; import org.onosproject.net.flow.criteria.Criterion; import org.onosproject.net.flow.criteria.EthCriterion; import org.onosproject.net.flow.criteria.EthTypeCriterion; import org.onosproject.net.flow.criteria.IPCriterion; import org.onosproject.net.flow.criteria.MplsBosCriterion; import org.onosproject.net.flow.criteria.MplsCriterion; import org.onosproject.net.flow.criteria.PortCriterion; import org.onosproject.net.flow.criteria.VlanIdCriterion; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flowobjective.ForwardingObjective; import org.onosproject.net.flowobjective.ObjectiveError; import org.onosproject.net.group.Group; import org.onosproject.net.group.GroupKey; import org.slf4j.Logger; /** * Driver for software switch emulation of the OFDPA 2.0 pipeline. * The software switch is the CPqD OF 1.3 switch. */ public class CpqdOFDPA2Pipeline extends OFDPA2Pipeline { private final Logger log = getLogger(getClass()); /* * Cpqd emulation does not require the non-OF standard rules for * matching untagged packets. * * (non-Javadoc) * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processVlanIdFilter */ @Override protected List<FlowRule> processVlanIdFilter(PortCriterion portCriterion, VlanIdCriterion vidCriterion, VlanId assignedVlan, ApplicationId applicationId) { List<FlowRule> rules = new ArrayList<FlowRule>(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector.matchVlanId(vidCriterion.vlanId()); treatment.transition(TMAC_TABLE); VlanId storeVlan = null; if (vidCriterion.vlanId() == VlanId.NONE) { // untagged packets are assigned vlans treatment.pushVlan().setVlanId(assignedVlan); storeVlan = assignedVlan; } else { storeVlan = vidCriterion.vlanId(); } // ofdpa cannot match on ALL portnumber, so we need to use separate // rules for each port. List<PortNumber> portnums = new ArrayList<PortNumber>(); if (portCriterion.port() == PortNumber.ALL) { for (Port port : deviceService.getPorts(deviceId)) { if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) { portnums.add(port.number()); } } } else { portnums.add(portCriterion.port()); } for (PortNumber pnum : portnums) { // update storage port2Vlan.put(pnum, storeVlan); Set<PortNumber> vlanPorts = vlan2Port.get(storeVlan); if (vlanPorts == null) { vlanPorts = Collections.newSetFromMap( new ConcurrentHashMap<PortNumber, Boolean>()); vlanPorts.add(pnum); vlan2Port.put(storeVlan, vlanPorts); } else { vlanPorts.add(pnum); } // create rest of flowrule selector.matchInPort(pnum); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(DEFAULT_PRIORITY) .fromApp(applicationId) .makePermanent() .forTable(VLAN_TABLE).build(); rules.add(rule); } return rules; } /* * Cpqd emulation does not handle vlan tags and mpls labels correctly. * Workaround requires popping off the VLAN tags in the TMAC table. * * (non-Javadoc) * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processEthDstFilter */ @Override protected List<FlowRule> processEthDstFilter(PortCriterion portCriterion, EthCriterion ethCriterion, VlanIdCriterion vidCriterion, VlanId assignedVlan, ApplicationId applicationId) { //handling untagged packets via assigned VLAN if (vidCriterion.vlanId() == VlanId.NONE) { vidCriterion = (VlanIdCriterion) Criteria.matchVlanId(assignedVlan); } // ofdpa cannot match on ALL portnumber, so we need to use separate // rules for each port. List<PortNumber> portnums = new ArrayList<PortNumber>(); if (portCriterion.port() == PortNumber.ALL) { for (Port port : deviceService.getPorts(deviceId)) { if (port.number().toLong() > 0 && port.number().toLong() < OFPP_MAX) { portnums.add(port.number()); } } } else { portnums.add(portCriterion.port()); } List<FlowRule> rules = new ArrayList<FlowRule>(); for (PortNumber pnum : portnums) { // for unicast IP packets TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector.matchInPort(pnum); selector.matchVlanId(vidCriterion.vlanId()); selector.matchEthType(Ethernet.TYPE_IPV4); selector.matchEthDst(ethCriterion.mac()); /* * Note: CpqD switches do not handle MPLS-related operation properly * for a packet with VLAN tag. We pop VLAN here as a workaround. * Side effect: HostService learns redundant hosts with same MAC but * different VLAN. No known side effect on the network reachability. */ treatment.popVlan(); treatment.transition(UNICAST_ROUTING_TABLE); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(DEFAULT_PRIORITY) .fromApp(applicationId) .makePermanent() .forTable(TMAC_TABLE).build(); rules.add(rule); //for MPLS packets selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); selector.matchInPort(pnum); selector.matchVlanId(vidCriterion.vlanId()); selector.matchEthType(Ethernet.MPLS_UNICAST); selector.matchEthDst(ethCriterion.mac()); // workaround here again treatment.popVlan(); treatment.transition(MPLS_TABLE_0); rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(DEFAULT_PRIORITY) .fromApp(applicationId) .makePermanent() .forTable(TMAC_TABLE).build(); rules.add(rule); } return rules; } /* * Cpqd emulation allows MPLS ecmp. * * (non-Javadoc) * @see org.onosproject.driver.pipeline.OFDPA2Pipeline#processEthTypeSpecific */ @Override protected Collection<FlowRule> processEthTypeSpecific(ForwardingObjective fwd) { TrafficSelector selector = fwd.selector(); EthTypeCriterion ethType = (EthTypeCriterion) selector.getCriterion(Criterion.Type.ETH_TYPE); if ((ethType == null) || (ethType.ethType().toShort() != Ethernet.TYPE_IPV4) && (ethType.ethType().toShort() != Ethernet.MPLS_UNICAST)) { log.warn("processSpecific: Unsupported forwarding objective criteria" + "ethType:{} in dev:{}", ethType, deviceId); fail(fwd, ObjectiveError.UNSUPPORTED); return Collections.emptySet(); } int forTableId = -1; TrafficSelector.Builder filteredSelector = DefaultTrafficSelector.builder(); if (ethType.ethType().toShort() == Ethernet.TYPE_IPV4) { filteredSelector.matchEthType(Ethernet.TYPE_IPV4) .matchIPDst(((IPCriterion) selector.getCriterion(Criterion.Type.IPV4_DST)).ip()); forTableId = UNICAST_ROUTING_TABLE; log.debug("processing IPv4 specific forwarding objective {} -> next:{}" + " in dev:{}", fwd.id(), fwd.nextId(), deviceId); } else { filteredSelector .matchEthType(Ethernet.MPLS_UNICAST) .matchMplsLabel(((MplsCriterion) selector.getCriterion(Criterion.Type.MPLS_LABEL)).label()); MplsBosCriterion bos = (MplsBosCriterion) selector .getCriterion(Criterion.Type.MPLS_BOS); if (bos != null) { filteredSelector.matchMplsBos(bos.mplsBos()); } forTableId = MPLS_TABLE_1; log.debug("processing MPLS specific forwarding objective {} -> next:{}" + " in dev {}", fwd.id(), fwd.nextId(), deviceId); } TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder(); if (fwd.treatment() != null) { for (Instruction i : fwd.treatment().allInstructions()) { /* * NOTE: OF-DPA does not support immediate instruction in * L3 unicast and MPLS table. */ tb.deferred().add(i); } } if (fwd.nextId() != null) { NextGroup next = flowObjectiveStore.getNextGroup(fwd.nextId()); List<Deque<GroupKey>> gkeys = appKryo.deserialize(next.data()); // we only need the top level group's key to point the flow to it Group group = groupService.getGroup(deviceId, gkeys.get(0).peekFirst()); if (group == null) { log.warn("The group left!"); fail(fwd, ObjectiveError.GROUPMISSING); return Collections.emptySet(); } tb.deferred().group(group.id()); } tb.transition(ACL_TABLE); FlowRule.Builder ruleBuilder = DefaultFlowRule.builder() .fromApp(fwd.appId()) .withPriority(fwd.priority()) .forDevice(deviceId) .withSelector(filteredSelector.build()) .withTreatment(tb.build()) .forTable(forTableId); if (fwd.permanent()) { ruleBuilder.makePermanent(); } else { ruleBuilder.makeTemporary(fwd.timeout()); } return Collections.singletonList(ruleBuilder.build()); } @Override protected void initializePipeline() { processPortTable(); // vlan table processing not required, as default is to drop packets // which can be accomplished without a table-miss-entry. processTmacTable(); processIpTable(); processMplsTable(); processBridgingTable(); processAclTable(); } protected void processPortTable() { FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); treatment.transition(VLAN_TABLE); FlowRule tmisse = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(PORT_TABLE).build(); ops = ops.add(tmisse); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized port table"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize port table"); } })); } protected void processTmacTable() { //table miss entry FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); treatment.transition(BRIDGING_TABLE); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(TMAC_TABLE).build(); ops = ops.add(rule); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized tmac table"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize tmac table"); } })); } protected void processIpTable() { //table miss entry FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); treatment.deferred().setOutput(PortNumber.CONTROLLER); treatment.transition(ACL_TABLE); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(UNICAST_ROUTING_TABLE).build(); ops = ops.add(rule); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized IP table"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize unicast IP table"); } })); } protected void processMplsTable() { //table miss entry FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); treatment.transition(MPLS_TABLE_1); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(MPLS_TABLE_0).build(); ops = ops.add(rule); treatment.transition(ACL_TABLE); rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(MPLS_TABLE_1).build(); ops = ops.add(rule); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized MPLS tables"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize MPLS tables"); } })); } private void processBridgingTable() { //table miss entry FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); treatment.transition(ACL_TABLE); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(BRIDGING_TABLE).build(); ops = ops.add(rule); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized Bridging table"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize Bridging table"); } })); } protected void processAclTable() { //table miss entry - catch all to executed action-set FlowRuleOperations.Builder ops = FlowRuleOperations.builder(); TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); selector = DefaultTrafficSelector.builder(); treatment = DefaultTrafficTreatment.builder(); FlowRule rule = DefaultFlowRule.builder() .forDevice(deviceId) .withSelector(selector.build()) .withTreatment(treatment.build()) .withPriority(LOWEST_PRIORITY) .fromApp(driverId) .makePermanent() .forTable(ACL_TABLE).build(); ops = ops.add(rule); flowRuleService.apply(ops.build(new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { log.info("Initialized Acl table"); } @Override public void onError(FlowRuleOperations ops) { log.info("Failed to initialize Acl table"); } })); } }
apache-2.0
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.application/test/osgi/enroute/trains/application/LayoutTest.java
1587
package osgi.enroute.trains.application; import junit.framework.TestCase; public class LayoutTest extends TestCase { public void testLayout() throws Exception { // String plan = IO.collect(LayoutTest.class.getResource("simple.txt")); // Tracks<Layout> track = new Tracks<>(plan, new LayoutAdapter()); // track.getRoot().get().layout(0, 0, null); // // assertEquals( "A00", track.getHandler("A00").segment.id); // assertEquals( 0, track.getHandler("A00").get().getPosition().x); // assertEquals( 0, track.getHandler("A00").get().getPosition().y); // // assertEquals( "X01", track.getHandler("X01").segment.id); // assertEquals( 1, track.getHandler("X01").get().getPosition().x); // assertEquals( 0, track.getHandler("X01").get().getPosition().y); // // assertEquals( "B00", track.getHandler("B00").segment.id); // assertEquals( 2, track.getHandler("B00").get().getPosition().x); // assertEquals( 0, track.getHandler("B00").get().getPosition().y); // // assertEquals( "C00", track.getHandler("C00").segment.id); // assertEquals( 2, track.getHandler("C00").get().getPosition().x); // assertEquals( 1, track.getHandler("C00").get().getPosition().y); // // assertEquals( "C01", track.getHandler("C01").segment.id); // assertEquals( 3, track.getHandler("C01").get().getPosition().x); // assertEquals( 1, track.getHandler("C01").get().getPosition().y); // // assertEquals( "X02", track.getHandler("X02").segment.id); // assertEquals( 4, track.getHandler("X02").get().getPosition().x); // assertEquals( 0, track.getHandler("X02").get().getPosition().y); } }
apache-2.0
shakamunyi/beam
sdks/java/core/src/main/java/com/google/cloud/dataflow/sdk/transforms/Sample.java
9198
/* * 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 com.google.cloud.dataflow.sdk.transforms; import com.google.cloud.dataflow.sdk.coders.BigEndianIntegerCoder; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderRegistry; import com.google.cloud.dataflow.sdk.coders.IterableCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.coders.VoidCoder; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.PCollection; import com.google.cloud.dataflow.sdk.values.PCollectionView; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * {@code PTransform}s for taking samples of the elements in a * {@code PCollection}, or samples of the values associated with each * key in a {@code PCollection} of {@code KV}s. **/ public class Sample { /** * {@code Sample#any(long)} takes a {@code PCollection<T>} and a limit, and * produces a new {@code PCollection<T>} containing up to limit * elements of the input {@code PCollection}. * * <p>If limit is greater than or equal to the size of the input * {@code PCollection}, then all the input's elements will be selected. * * <p>All of the elements of the output {@code PCollection} should fit into * main memory of a single worker machine. This operation does not * run in parallel. * * <p>Example of use: * <pre> {@code * PCollection<String> input = ...; * PCollection<String> output = input.apply(Sample.<String>any(100)); * } </pre> * * @param <T> the type of the elements of the input and output * {@code PCollection}s * @param limit the number of elements to take from the input */ public static <T> PTransform<PCollection<T>, PCollection<T>> any(long limit) { return new SampleAny<>(limit); } /** * Returns a {@code PTransform} that takes a {@code PCollection<T>}, * selects {@code sampleSize} elements, uniformly at random, and returns a * {@code PCollection<Iterable<T>>} containing the selected elements. * If the input {@code PCollection} has fewer than * {@code sampleSize} elements, then the output {@code Iterable<T>} * will be all the input's elements. * * <p>Example of use: * <pre> {@code * PCollection<String> pc = ...; * PCollection<Iterable<String>> sampleOfSize10 = * pc.apply(Sample.fixedSizeGlobally(10)); * } </pre> * * @param sampleSize the number of elements to select; must be {@code >= 0} * @param <T> the type of the elements */ public static <T> PTransform<PCollection<T>, PCollection<Iterable<T>>> fixedSizeGlobally(int sampleSize) { return Combine.globally(new FixedSizedSampleFn<T>(sampleSize)); } /** * Returns a {@code PTransform} that takes an input * {@code PCollection<KV<K, V>>} and returns a * {@code PCollection<KV<K, Iterable<V>>>} that contains an output * element mapping each distinct key in the input * {@code PCollection} to a sample of {@code sampleSize} values * associated with that key in the input {@code PCollection}, taken * uniformly at random. If a key in the input {@code PCollection} * has fewer than {@code sampleSize} values associated with it, then * the output {@code Iterable<V>} associated with that key will be * all the values associated with that key in the input * {@code PCollection}. * * <p>Example of use: * <pre> {@code * PCollection<KV<String, Integer>> pc = ...; * PCollection<KV<String, Iterable<Integer>>> sampleOfSize10PerKey = * pc.apply(Sample.<String, Integer>fixedSizePerKey()); * } </pre> * * @param sampleSize the number of values to select for each * distinct key; must be {@code >= 0} * @param <K> the type of the keys * @param <V> the type of the values */ public static <K, V> PTransform<PCollection<KV<K, V>>, PCollection<KV<K, Iterable<V>>>> fixedSizePerKey(int sampleSize) { return Combine.perKey(new FixedSizedSampleFn<V>(sampleSize)); } ///////////////////////////////////////////////////////////////////////////// /** * A {@link PTransform} that takes a {@code PCollection<T>} and a limit, and * produces a new {@code PCollection<T>} containing up to limit * elements of the input {@code PCollection}. */ public static class SampleAny<T> extends PTransform<PCollection<T>, PCollection<T>> { private final long limit; /** * Constructs a {@code SampleAny<T>} PTransform that, when applied, * produces a new PCollection containing up to {@code limit} * elements of its input {@code PCollection}. */ private SampleAny(long limit) { Preconditions.checkArgument(limit >= 0, "Expected non-negative limit, received %s.", limit); this.limit = limit; } @Override public PCollection<T> apply(PCollection<T> in) { PCollectionView<Iterable<T>> iterableView = in.apply(View.<T>asIterable()); return in.getPipeline() .apply(Create.of((Void) null).withCoder(VoidCoder.of())) .apply(ParDo .withSideInputs(iterableView) .of(new SampleAnyDoFn<>(limit, iterableView))) .setCoder(in.getCoder()); } } /** * A {@link DoFn} that returns up to limit elements from the side input PCollection. */ private static class SampleAnyDoFn<T> extends DoFn<Void, T> { long limit; final PCollectionView<Iterable<T>> iterableView; public SampleAnyDoFn(long limit, PCollectionView<Iterable<T>> iterableView) { this.limit = limit; this.iterableView = iterableView; } @Override public void processElement(ProcessContext c) { for (T i : c.sideInput(iterableView)) { if (limit-- <= 0) { break; } c.output(i); } } } /** * {@code CombineFn} that computes a fixed-size sample of a * collection of values. * * @param <T> the type of the elements */ public static class FixedSizedSampleFn<T> extends CombineFn<T, Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>>, Iterable<T>> { private final Top.TopCombineFn<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> topCombineFn; private final Random rand = new Random(); private FixedSizedSampleFn(int sampleSize) { if (sampleSize < 0) { throw new IllegalArgumentException("sample size must be >= 0"); } topCombineFn = new Top.TopCombineFn<KV<Integer, T>, SerializableComparator<KV<Integer, T>>>( sampleSize, new KV.OrderByKey<Integer, T>()); } @Override public Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> createAccumulator() { return topCombineFn.createAccumulator(); } @Override public Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> addInput( Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> accumulator, T input) { accumulator.addInput(KV.of(rand.nextInt(), input)); return accumulator; } @Override public Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> mergeAccumulators( Iterable<Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>>> accumulators) { return topCombineFn.mergeAccumulators(accumulators); } @Override public Iterable<T> extractOutput( Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>> accumulator) { List<T> out = new ArrayList<>(); for (KV<Integer, T> element : accumulator.extractOutput()) { out.add(element.getValue()); } return out; } @Override public Coder<Top.BoundedHeap<KV<Integer, T>, SerializableComparator<KV<Integer, T>>>> getAccumulatorCoder(CoderRegistry registry, Coder<T> inputCoder) { return topCombineFn.getAccumulatorCoder( registry, KvCoder.of(BigEndianIntegerCoder.of(), inputCoder)); } @Override public Coder<Iterable<T>> getDefaultOutputCoder( CoderRegistry registry, Coder<T> inputCoder) { return IterableCoder.of(inputCoder); } } }
apache-2.0
unlimitedggames/gdxjam-ugg
core/src/com/ugg/gdxjam/model/Logger.java
582
package com.ugg.gdxjam.model; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.*; public class Logger { private static Logger _instance = null; private static Application _app = null; private static String _appName = "GDXJam-UGG"; protected Logger(){ } public static Logger getInstance(){ if(_instance == null || _app != Gdx.app){ _instance = new Logger(); _app = Gdx.app; } return _instance; } public void log(String message){ Gdx.app.log(_appName, message); } public void error(String message){ Gdx.app.error(_appName, message); } }
apache-2.0
gogamoga/velocity-tools-1.4
src/java/org/apache/velocity/tools/view/ToolboxManager.java
1826
package org.apache.velocity.tools.view; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Map; /** * Common interface for toolbox manager implementations. * * @author Nathan Bubna * @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a> * @author <a href="mailto:sidler@teamup.com">Gabe Sidler</a> * @author <a href="mailto:henning@schmiedehausen.org">Henning P. Schmiedehausen</a> * @version $Id$ */ public interface ToolboxManager { /** * Adds a tool to be managed */ void addTool(ToolInfo info); /** * Adds a data object for the context. * * @param info An object that implements ToolInfo */ void addData(ToolInfo info); /** * Retrieves a map of the tools and data being managed. Tools * that have an init(Object) method will be (re)initialized * using the specified initData. * * @param initData data used to initialize tools * @return the created ToolboxContext * @since VelocityTools 1.2 */ Map getToolbox(Object initData); }
apache-2.0
emil-wcislo/sbql4j8
sbql4j8/src/main/openjdk/sbql4j8/com/sun/tools/doclets/formats/html/NestedClassWriterImpl.java
7520
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sbql4j8.com.sun.tools.doclets.formats.html; import java.io.*; import sbql4j8.com.sun.javadoc.*; import sbql4j8.com.sun.tools.doclets.formats.html.markup.*; import sbql4j8.com.sun.tools.doclets.internal.toolkit.*; import sbql4j8.com.sun.tools.doclets.internal.toolkit.util.*; /** * Writes nested class documentation in HTML format. * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> * * @author Robert Field * @author Atul M Dambalkar * @author Jamie Ho (rewrite) * @author Bhavesh Patel (Modified) */ public class NestedClassWriterImpl extends AbstractMemberWriter implements MemberSummaryWriter { public NestedClassWriterImpl(SubWriterHolderWriter writer, ClassDoc classdoc) { super(writer, classdoc); } public NestedClassWriterImpl(SubWriterHolderWriter writer) { super(writer); } /** * {@inheritDoc} */ public Content getMemberSummaryHeader(ClassDoc classDoc, Content memberSummaryTree) { memberSummaryTree.addContent(HtmlConstants.START_OF_NESTED_CLASS_SUMMARY); Content memberTree = writer.getMemberTreeHeader(); writer.addSummaryHeader(this, classDoc, memberTree); return memberTree; } /** * Close the writer. */ public void close() throws IOException { writer.close(); } public int getMemberKind() { return VisibleMemberMap.INNERCLASSES; } /** * {@inheritDoc} */ public void addSummaryLabel(Content memberTree) { Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING, writer.getResource("doclet.Nested_Class_Summary")); memberTree.addContent(label); } /** * {@inheritDoc} */ public String getTableSummary() { return configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Nested_Class_Summary"), configuration.getText("doclet.nested_classes")); } /** * {@inheritDoc} */ public Content getCaption() { return configuration.getResource("doclet.Nested_Classes"); } /** * {@inheritDoc} */ public String[] getSummaryTableHeader(ProgramElementDoc member) { String[] header; if (member.isInterface()) { header = new String[] { writer.getModifierTypeHeader(), configuration.getText("doclet.0_and_1", configuration.getText("doclet.Interface"), configuration.getText("doclet.Description")) }; } else { header = new String[] { writer.getModifierTypeHeader(), configuration.getText("doclet.0_and_1", configuration.getText("doclet.Class"), configuration.getText("doclet.Description")) }; } return header; } /** * {@inheritDoc} */ public void addSummaryAnchor(ClassDoc cd, Content memberTree) { memberTree.addContent(writer.getMarkerAnchor( SectionName.NESTED_CLASS_SUMMARY)); } /** * {@inheritDoc} */ public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) { inheritedTree.addContent(writer.getMarkerAnchor( SectionName.NESTED_CLASSES_INHERITANCE, cd.qualifiedName())); } /** * {@inheritDoc} */ public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) { Content classLink = writer.getPreQualifiedClassLink( LinkInfoImpl.Kind.MEMBER, cd, false); Content label = new StringContent(cd.isInterface() ? configuration.getText("doclet.Nested_Classes_Interface_Inherited_From_Interface") : configuration.getText("doclet.Nested_Classes_Interfaces_Inherited_From_Class")); Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING, label); labelHeading.addContent(writer.getSpace()); labelHeading.addContent(classLink); inheritedTree.addContent(labelHeading); } /** * {@inheritDoc} */ protected void addSummaryLink(LinkInfoImpl.Kind context, ClassDoc cd, ProgramElementDoc member, Content tdSummary) { Content memberLink = HtmlTree.SPAN(HtmlStyle.memberNameLink, writer.getLink(new LinkInfoImpl(configuration, context, (ClassDoc)member))); Content code = HtmlTree.CODE(memberLink); tdSummary.addContent(code); } /** * {@inheritDoc} */ protected void addInheritedSummaryLink(ClassDoc cd, ProgramElementDoc member, Content linksTree) { linksTree.addContent( writer.getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.MEMBER, (ClassDoc)member))); } /** * {@inheritDoc} */ protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) { ClassDoc cd = (ClassDoc)member; addModifierAndType(cd, null, tdSummaryType); } /** * {@inheritDoc} */ protected Content getDeprecatedLink(ProgramElementDoc member) { return writer.getQualifiedClassLink(LinkInfoImpl.Kind.MEMBER, (ClassDoc)member); } /** * {@inheritDoc} */ protected Content getNavSummaryLink(ClassDoc cd, boolean link) { if (link) { if (cd == null) { return writer.getHyperLink( SectionName.NESTED_CLASS_SUMMARY, writer.getResource("doclet.navNested")); } else { return writer.getHyperLink( SectionName.NESTED_CLASSES_INHERITANCE, cd.qualifiedName(), writer.getResource("doclet.navNested")); } } else { return writer.getResource("doclet.navNested"); } } /** * {@inheritDoc} */ protected void addNavDetailLink(boolean link, Content liNav) { } }
apache-2.0
makeok/zhw-util
src/com/zhw/core/net/cpumem/example1/MonitorInfoBean.java
2440
package com.zhw.core.net.cpumem.example1; /** */ /** * 监视信息的JavaBean类. * @author amg * @version 1.0 * Creation date: 2008-4-25 - 上午10:37:00 */ public class MonitorInfoBean { /** *//** 可使用内存. */ private long totalMemory; /** *//** 剩余内存. */ private long freeMemory; /** *//** 最大可使用内存. */ private long maxMemory; /** *//** 操作系统. */ private String osName; /** *//** 总的物理内存. */ private long totalMemorySize; /** *//** 剩余的物理内存. */ private long freePhysicalMemorySize; /** *//** 已使用的物理内存. */ private long usedMemory; /** *//** 线程总数. */ private int totalThread; /** *//** cpu使用率. */ private double cpuRatio; public long getFreeMemory() { return freeMemory; } public void setFreeMemory(long freeMemory) { this.freeMemory = freeMemory; } public long getFreePhysicalMemorySize() { return freePhysicalMemorySize; } public void setFreePhysicalMemorySize(long freePhysicalMemorySize) { this.freePhysicalMemorySize = freePhysicalMemorySize; } public long getMaxMemory() { return maxMemory; } public void setMaxMemory(long maxMemory) { this.maxMemory = maxMemory; } public String getOsName() { return osName; } public void setOsName(String osName) { this.osName = osName; } public long getTotalMemory() { return totalMemory; } public void setTotalMemory(long totalMemory) { this.totalMemory = totalMemory; } public long getTotalMemorySize() { return totalMemorySize; } public void setTotalMemorySize(long totalMemorySize) { this.totalMemorySize = totalMemorySize; } public int getTotalThread() { return totalThread; } public void setTotalThread(int totalThread) { this.totalThread = totalThread; } public long getUsedMemory() { return usedMemory; } public void setUsedMemory(long usedMemory) { this.usedMemory = usedMemory; } public double getCpuRatio() { return cpuRatio; } public void setCpuRatio(double cpuRatio) { this.cpuRatio = cpuRatio; } }
apache-2.0
obazoud/elasticsearch-river-git
src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
1060
package com.bazoud.elasticsearch.river.git.beans; import java.io.File; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.elasticsearch.client.Client; import com.google.common.base.Optional; import lombok.Data; /** * @author Olivier Bazoud */ @Data @SuppressWarnings("PMD.UnusedPrivateField") public class Context { private String name; private String uri; private File projectPath; private Repository repository; private String workingDir = System.getProperty("user.home") + File.separator + ".elasticsearch-river-git"; private Collection<Ref> refs; private Client client; private Optional<Pattern> issuePattern = Optional.absent(); private String issueRegex; private boolean indexingDiff; private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); private String type = "git"; private String riverName; private String riverIndexName; }
apache-2.0
atomicjets/distributed-graph-analytics
dga-giraph/src/main/java/com/soteradefense/dga/lc/LeafCompressionComputation.java
4864
/* * * 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 com.soteradefense.dga.lc; import com.soteradefense.dga.DGALoggingUtil; import org.apache.giraph.comm.WorkerClientRequestProcessor; import org.apache.giraph.edge.Edge; import org.apache.giraph.graph.BasicComputation; import org.apache.giraph.graph.GraphState; import org.apache.giraph.graph.GraphTaskManager; import org.apache.giraph.graph.Vertex; import org.apache.giraph.worker.WorkerAggregatorUsage; import org.apache.giraph.worker.WorkerContext; import org.apache.giraph.worker.WorkerGlobalCommUsage; import org.apache.hadoop.io.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * Leaf Compression is an analytic used to compress a graph; nodes on the periphery of the graph that do not show an * extensive network of connections from them will inform the nodes connected to them to remove them from the graph * <p/> * This cycle continues until all leaves have been pruned. */ public class LeafCompressionComputation extends BasicComputation<Text, Text, Text, Text> { private static Logger logger = LoggerFactory.getLogger(LeafCompressionComputation.class); @Override public void initialize(GraphState graphState, WorkerClientRequestProcessor<Text, Text, Text> workerClientRequestProcessor, GraphTaskManager<Text, Text, Text> graphTaskManager, WorkerGlobalCommUsage workerGlobalCommUsage, WorkerContext workerContext) { super.initialize(graphState, workerClientRequestProcessor, graphTaskManager, workerGlobalCommUsage, workerContext); DGALoggingUtil.setDGALogLevel(getConf()); } @Override public void compute(Vertex<Text, Text, Text> vertex, Iterable<Text> messages) throws IOException { try { // Check to see if we received any messages from connected nodes notifying us // that they have only a single edge, and can subsequently be pruned from the graph for (Text incomingMessage : messages) { Text messageVertex = new Text(incomingMessage.toString().split(":")[0]); int messageValue = getVertexValue(incomingMessage.toString().split(":")[1]); vertex.setValue(new Text(String.format("%d", getVertexValue(vertex.getValue().toString()) + 1 + messageValue))); // Remove the vertex and its corresponding edge removeVertexRequest(messageVertex); vertex.removeEdges(messageVertex); } // Broadcast the edges if we only have a single edge sendEdges(vertex); } catch (Exception e) { System.err.println(e.toString()); } } /** * Inform each node we are connected to if we only have one edge so that we can be purged from the graph, or vote * to halt * * @param vertex The current vertex being operated upon by the compute method */ private void sendEdges(Vertex<Text, Text, Text> vertex) { int vertexValue = getVertexValue(vertex.getValue().toString()); if (vertex.getNumEdges() == 1 && vertexValue != -1) { for (Edge<Text, Text> edge : vertex.getEdges()) { sendMessage(edge.getTargetVertexId(), new Text(vertex.getId().toString() + ":" + vertexValue)); } logger.debug("{} is being deleted.", vertex.getId()); vertex.setValue(new Text("-1")); // This node will never vote to halt, but will simply be deleted. } else if (vertexValue != -1) { // If we aren't being imminently deleted logger.debug("{} is still in the graph.", vertex.getId()); vertex.voteToHalt(); } } /** * Converts a vertex value from a string to an int. * * @param value vertex value as a string. * @return integer vertex value. */ private int getVertexValue(String value) { int vertexValue = 0; if (value != null && !value.equals("")) { vertexValue = Integer.parseInt(value); } return vertexValue; } }
apache-2.0
maheshika/carbon-mediation
components/mediation-ui/mediators-ui/org.wso2.carbon.mediator.bam.ui/src/main/java/org/wso2/carbon/mediator/bam/ui/BamMediator.java
5218
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.mediator.bam.ui; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.synapse.SynapseConstants; import org.wso2.carbon.mediator.service.MediatorException; import org.wso2.carbon.mediator.service.ui.AbstractMediator; import javax.xml.namespace.QName; /** * Object used to store mediator sequence information in UI side */ public class BamMediator extends AbstractMediator { public static final QName NAME_Q = new QName("name"); private String serverProfile = ""; private String streamName = ""; private String streamVersion = ""; public String getServerProfile(){ return this.serverProfile; } public void setServerProfile(String serverProfile1){ this.serverProfile = serverProfile1; } public String getStreamName(){ return this.streamName; } public void setStreamName(String streamName){ this.streamName = streamName; } public String getStreamVersion(){ return this.streamVersion; } public void setStreamVersion(String streamVersion){ this.streamVersion = streamVersion; } public String getTagLocalName() { return "bam"; } public OMElement serialize(OMElement parent) { OMElement bamElement = fac.createOMElement("bam", synNS); saveTracingState(bamElement, this); OMElement serverProfileElement = serializeServerProfile(); serverProfileElement.addChild(serializeStreamConfiguration()); bamElement.addChild(serverProfileElement); if (parent != null) { parent.addChild(bamElement); } /*else { String msg = "The parent element is not specified"; throw new MediatorException(msg); }*/ return bamElement; } public void build(OMElement omElement) { OMElement profileElement = omElement.getFirstChildWithName( new QName(SynapseConstants.SYNAPSE_NAMESPACE, "serverProfile")); if (profileElement != null){ processProfile(profileElement); } else { String msg = "The 'serverProfile' element is not specified"; throw new MediatorException(msg); } processAuditStatus(this, omElement); } private void processProfile(OMElement profile){ OMAttribute pathAttr = profile.getAttribute(NAME_Q); if(pathAttr != null){ String pathValue = pathAttr.getAttributeValue(); this.setServerProfile(pathValue); OMElement streamElement = profile.getFirstChildWithName( new QName(SynapseConstants.SYNAPSE_NAMESPACE, "streamConfig")); if(streamElement != null){ processStreamConfiguration(streamElement); } else { String msg = "The 'streamConfig' element is not specified"; throw new MediatorException(msg); } } else { String msg = "The 'name' attribute of Profile is not specified"; throw new MediatorException(msg); } } private void processStreamConfiguration(OMElement streamConfig){ OMAttribute streamNameAttr = streamConfig.getAttribute(NAME_Q); OMAttribute streamVersionAttr = streamConfig.getAttribute(new QName("version")); if(streamNameAttr != null && streamVersionAttr != null){ String nameValue = streamNameAttr.getAttributeValue(); String versionValue = streamVersionAttr.getAttributeValue(); this.setStreamName(nameValue); this.setStreamVersion(versionValue); } else { String msg = "The stream name or stream version attributes are not specified"; throw new MediatorException(msg); } } private OMElement serializeServerProfile(){ OMElement profileElement = fac.createOMElement("serverProfile", synNS); profileElement.addAttribute("name", this.serverProfile, nullNS); return profileElement; } private OMElement serializeStreamConfiguration(){ OMElement streamConfigElement = fac.createOMElement("streamConfig",synNS); streamConfigElement.addAttribute("name", this.streamName, nullNS); streamConfigElement.addAttribute("version", this.streamVersion, nullNS); return streamConfigElement; } }
apache-2.0
tinapgaara/Yelp-Review-Analysis-and-Recommendation
BigDataOnline/src/bigdata/StopWords.java
663
package bigdata; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class StopWords { private static HashSet<String> stopWords; private static final String STOPWORD_FILE = "data/stopwords.txt"; static { stopWords = new HashSet<String>(); try { BufferedReader reader = new BufferedReader(new FileReader(STOPWORD_FILE)); String line; while ((line = reader.readLine()) != null) stopWords.add(line); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public static boolean checkStop(String word) { return stopWords.contains(word); } }
apache-2.0
dahlstrom-g/intellij-community
platform/util/src/com/intellij/openapi/diagnostic/Log4jBasedLogger.java
1902
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diagnostic; import org.apache.log4j.Level; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class Log4jBasedLogger extends Logger { protected final org.apache.log4j.Logger myLogger; public Log4jBasedLogger(@NotNull org.apache.log4j.Logger delegate) { myLogger = delegate; } @Override public boolean isDebugEnabled() { return myLogger.isDebugEnabled(); } @Override public void debug(@NonNls String message) { myLogger.debug(message); } @Override public void debug(@Nullable Throwable t) { myLogger.debug("", t); } @Override public void debug(@NonNls String message, @Nullable Throwable t) { myLogger.debug(message, t); } @Override public final boolean isTraceEnabled() { return myLogger.isTraceEnabled(); } @Override public void trace(String message) { myLogger.trace(message); } @Override public void trace(@Nullable Throwable t) { myLogger.trace("", t); } @Override public void info(@NonNls String message) { myLogger.info(message); } @Override public void info(@NonNls String message, @Nullable Throwable t) { myLogger.info(message, t); } @Override public void warn(@NonNls String message, @Nullable Throwable t) { myLogger.warn(message, t); } @Override public void error(@NonNls String message, @Nullable Throwable t, @NonNls String @NotNull ... details) { @NonNls String fullMessage = details.length > 0 ? message + "\nDetails: " + String.join("\n", details) : message; myLogger.error(fullMessage, t); } @Override public final void setLevel(@NotNull Level level) { myLogger.setLevel(level); } }
apache-2.0
alekseyld/CollegeTimetable
domain/src/main/java/com/alekseyld/collegetimetable/entity/Day.java
1000
package com.alekseyld.collegetimetable.entity; import java.util.ArrayList; import java.util.List; /** * Created by Alekseyld on 21.09.2017. */ public class Day { private int id; private String date; private List<Lesson> dayLessons = new ArrayList<>(); public String getDate() { return date; } public Day setDate(String date) { this.date = date; return this; } public int getId() { return id; } public Day setId(int id) { this.id = id; return this; } public List<Lesson> getDayLessons() { return dayLessons; } public Day setDayLessons(List<Lesson> dayLessons) { this.dayLessons = dayLessons; return this; } public String getDateFirstUpperCase(){ if(date == null || date.isEmpty()) return "";//или return word; return (date.substring(0, 1).toUpperCase() + date.substring(1).toLowerCase()) .replace(" ", ""); } }
apache-2.0
desruisseaux/sis
core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/metadata/RS_ReferenceSystem.java
3590
/* * 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.sis.internal.jaxb.metadata; import javax.xml.bind.annotation.XmlElementRef; import org.opengis.referencing.ReferenceSystem; import org.apache.sis.internal.jaxb.gco.PropertyType; import org.apache.sis.internal.jaxb.metadata.replace.ReferenceSystemMetadata; /** * JAXB adapter mapping implementing class to the GeoAPI interface. See * package documentation for more information about JAXB and interface. * * @author Guilhem Legal (Geomatys) * @since 0.3 * @version 0.4 * @module */ public final class RS_ReferenceSystem extends PropertyType<RS_ReferenceSystem, ReferenceSystem> { /** * Empty constructor for JAXB only. */ public RS_ReferenceSystem() { } /** * Returns the GeoAPI interface which is bound by this adapter. * This method is indirectly invoked by the private constructor * below, so it shall not depend on the state of this object. * * @return {@code ReferenceSystem.class} */ @Override protected Class<ReferenceSystem> getBoundType() { return ReferenceSystem.class; } /** * Wraps a Reference System value in a {@code MD_ReferenceSystem} element at marshalling-time. * * @param metadata The metadata value to marshal. */ protected RS_ReferenceSystem(final ReferenceSystem metadata) { super(metadata); } /** * Invoked by {@link PropertyType} at marshalling time for wrapping the given metadata value * in a {@code <gmd:RS_ReferenceSystem>} XML element. * * @param metadata The metadata element to marshall. * @return A {@code PropertyType} wrapping the given the metadata element. */ @Override protected RS_ReferenceSystem wrap(ReferenceSystem metadata) { return new RS_ReferenceSystem(metadata); } /** * Invoked by JAXB at marshalling time for getting the actual metadata to write * inside the {@code <gmd:RS_ReferenceSystem>} XML element. * This is the value or a copy of the value given in argument to the {@code wrap} method. * * @return The metadata to be marshalled. */ @XmlElementRef public ReferenceSystemMetadata getElement() { final ReferenceSystem metadata = this.metadata; if (metadata == null) { return null; } else if (metadata instanceof ReferenceSystemMetadata) { return (ReferenceSystemMetadata) metadata; } else { return new ReferenceSystemMetadata(metadata); } } /** * Invoked by JAXB at unmarshalling time for storing the result temporarily. * * @param metadata The unmarshalled metadata. */ public void setElement(final ReferenceSystemMetadata metadata) { this.metadata = metadata; } }
apache-2.0
phax/ph-web
ph-httpclient/src/main/java/com/helger/httpclient/HttpClientFactory.java
14830
/* * Copyright (C) 2016-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.httpclient; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.RequestAcceptEncoding; import org.apache.http.client.protocol.RequestAddCookies; import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.SchemePortResolver; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLInitializationException; import org.apache.http.impl.NoConnectionReuseStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.apache.http.impl.conn.DefaultRoutePlanner; import org.apache.http.impl.conn.DefaultSchemePortResolver; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.SystemDefaultDnsResolver; import org.apache.http.protocol.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.collection.impl.ICommonsSet; import com.helger.http.tls.ITLSConfigurationMode; import com.helger.httpclient.HttpClientRetryHandler.ERetryMode; /** * A factory for creating {@link CloseableHttpClient} that is e.g. to be used in * the {@link HttpClientManager}. * * @author Philip Helger */ @NotThreadSafe public class HttpClientFactory implements IHttpClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger (HttpClientFactory.class); private final HttpClientSettings m_aSettings; /** * Default constructor. */ public HttpClientFactory () { this (new HttpClientSettings ()); } /** * Constructor with explicit settings. * * @param aSettings * The settings to be used. May not be <code>null</code>. */ public HttpClientFactory (@Nonnull final HttpClientSettings aSettings) { ValueEnforcer.notNull (aSettings, "Settings"); m_aSettings = aSettings; } /** * Create the scheme to port resolver. * * @return Never <code>null</code>. * @since 9.1.1 */ @Nonnull public SchemePortResolver createSchemePortResolver () { return DefaultSchemePortResolver.INSTANCE; } @Nullable public LayeredConnectionSocketFactory createSSLFactory () { LayeredConnectionSocketFactory aSSLFactory = null; try { // First try with a custom SSL context final SSLContext aSSLContext = m_aSettings.getSSLContext (); if (aSSLContext != null) { // Choose correct TLS configuration mode ITLSConfigurationMode aTLSConfigMode = m_aSettings.getTLSConfigurationMode (); if (aTLSConfigMode == null) aTLSConfigMode = HttpClientSettings.DEFAULT_TLS_CONFIG_MODE; // Custom hostname verifier preferred HostnameVerifier aHostnameVerifier = m_aSettings.getHostnameVerifier (); if (aHostnameVerifier == null) aHostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier (); if (LOGGER.isDebugEnabled ()) { LOGGER.debug ("Using the following TLS versions: " + aTLSConfigMode.getAllTLSVersionIDs ()); LOGGER.debug ("Using the following TLS cipher suites: " + aTLSConfigMode.getAllCipherSuites ()); LOGGER.debug ("Using the following hostname verifier: " + aHostnameVerifier); } aSSLFactory = new SSLConnectionSocketFactory (aSSLContext, aTLSConfigMode.getAllTLSVersionIDsAsArray (), aTLSConfigMode.getAllCipherSuitesAsArray (), aHostnameVerifier); } } catch (final SSLInitializationException ex) { // Fall through LOGGER.warn ("Failed to init custom SSLConnectionSocketFactory - falling back to default SSLConnectionSocketFactory", ex); } if (aSSLFactory == null) { // No custom SSL context present - use system defaults try { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Trying SSLConnectionSocketFactory.getSystemSocketFactory ()"); aSSLFactory = SSLConnectionSocketFactory.getSystemSocketFactory (); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Using SSL socket factory with an SSL context based on system propertiesas described in JSSE Reference Guide."); } catch (final SSLInitializationException ex) { try { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Trying SSLConnectionSocketFactory.getSocketFactory ()"); aSSLFactory = SSLConnectionSocketFactory.getSocketFactory (); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Using SSL socket factory with an SSL context based on the standard JSSEtrust material (cacerts file in the security properties directory).System properties are not taken into consideration."); } catch (final SSLInitializationException ex2) { // Fall through } } } return aSSLFactory; } /** * @return The connection builder used by the * {@link PoolingHttpClientConnectionManager} to create the default * connection configuration. */ @Nonnull public ConnectionConfig.Builder createConnectionConfigBuilder () { return ConnectionConfig.custom () .setMalformedInputAction (CodingErrorAction.IGNORE) .setUnmappableInputAction (CodingErrorAction.IGNORE) .setCharset (StandardCharsets.UTF_8); } /** * @return The default connection configuration used by the * {@link PoolingHttpClientConnectionManager}. */ @Nonnull public ConnectionConfig createConnectionConfig () { return createConnectionConfigBuilder ().build (); } /** * @return The DNS resolver to be used for * {@link PoolingHttpClientConnectionManager}. May be * <code>null</code> to use the default. * @since 8.8.0 */ @Nullable public DnsResolver createDNSResolver () { // If caching is active, use the default System resolver return m_aSettings.isUseDNSClientCache () ? SystemDefaultDnsResolver.INSTANCE : NonCachingDnsResolver.INSTANCE; } @Nonnull public HttpClientConnectionManager createConnectionManager (@Nonnull final LayeredConnectionSocketFactory aSSLFactory) { final Registry <ConnectionSocketFactory> aConSocketRegistry = RegistryBuilder.<ConnectionSocketFactory> create () .register ("http", PlainConnectionSocketFactory.getSocketFactory ()) .register ("https", aSSLFactory) .build (); final DnsResolver aDNSResolver = createDNSResolver (); final PoolingHttpClientConnectionManager aConnMgr = new PoolingHttpClientConnectionManager (aConSocketRegistry, aDNSResolver); aConnMgr.setDefaultMaxPerRoute (100); aConnMgr.setMaxTotal (200); aConnMgr.setValidateAfterInactivity (1000); final ConnectionConfig aConnectionConfig = createConnectionConfig (); aConnMgr.setDefaultConnectionConfig (aConnectionConfig); return aConnMgr; } @Nullable public ConnectionReuseStrategy createConnectionReuseStrategy () { if (m_aSettings.isUseKeepAlive ()) return DefaultClientConnectionReuseStrategy.INSTANCE; return NoConnectionReuseStrategy.INSTANCE; } @Nonnull public RequestConfig.Builder createRequestConfigBuilder () { return RequestConfig.custom () .setCookieSpec (CookieSpecs.DEFAULT) .setConnectionRequestTimeout (m_aSettings.getConnectionRequestTimeoutMS ()) .setConnectTimeout (m_aSettings.getConnectionTimeoutMS ()) .setSocketTimeout (m_aSettings.getSocketTimeoutMS ()) .setCircularRedirectsAllowed (false) .setRedirectsEnabled (m_aSettings.isFollowRedirects ()); } @Nonnull public RequestConfig createRequestConfig () { return createRequestConfigBuilder ().build (); } @Nullable public CredentialsProvider createCredentialsProvider () { final HttpHost aProxyHost = m_aSettings.getProxyHost (); final Credentials aProxyCredentials = m_aSettings.getProxyCredentials (); if (aProxyHost != null && aProxyCredentials != null) { final CredentialsProvider aCredentialsProvider = new BasicCredentialsProvider (); aCredentialsProvider.setCredentials (new AuthScope (aProxyHost), aProxyCredentials); return aCredentialsProvider; } return null; } @Nullable public HttpRequestRetryHandler createRequestRetryHandler (@Nonnegative final int nMaxRetries, @Nonnull final ERetryMode eRetryMode) { return new HttpClientRetryHandler (nMaxRetries, eRetryMode); } @Nonnull public HttpClientBuilder createHttpClientBuilder () { final LayeredConnectionSocketFactory aSSLFactory = createSSLFactory (); if (aSSLFactory == null) throw new IllegalStateException ("Failed to create SSL SocketFactory"); final SchemePortResolver aSchemePortResolver = createSchemePortResolver (); final HttpClientConnectionManager aConnMgr = createConnectionManager (aSSLFactory); final ConnectionReuseStrategy aConnectionReuseStrategy = createConnectionReuseStrategy (); final RequestConfig aRequestConfig = createRequestConfig (); final HttpHost aProxyHost = m_aSettings.getProxyHost (); final CredentialsProvider aCredentialsProvider = createCredentialsProvider (); HttpRoutePlanner aRoutePlanner = null; if (aProxyHost != null) { // If a route planner is used, the HttpClientBuilder MUST NOT use the // proxy, because this would have precedence if (m_aSettings.nonProxyHosts ().isEmpty ()) { // Proxy for all aRoutePlanner = new DefaultProxyRoutePlanner (aProxyHost, aSchemePortResolver); } else { // Proxy for all but non-proxy hosts // Clone set here to avoid concurrent modification final ICommonsSet <String> aNonProxyHosts = m_aSettings.nonProxyHosts ().getClone (); aRoutePlanner = new DefaultRoutePlanner (aSchemePortResolver) { @Override protected HttpHost determineProxy (@Nonnull final HttpHost aTarget, @Nonnull final HttpRequest aRequest, @Nonnull final HttpContext aContext) throws HttpException { final String sHostname = aTarget.getHostName (); if (aNonProxyHosts.contains (sHostname)) { // Return direct route if (LOGGER.isInfoEnabled ()) LOGGER.info ("Not using proxy host for route to '" + sHostname + "'"); return null; } return aProxyHost; } }; } } final HttpClientBuilder aHCB = HttpClients.custom () .setSchemePortResolver (aSchemePortResolver) .setConnectionManager (aConnMgr) .setDefaultRequestConfig (aRequestConfig) .setDefaultCredentialsProvider (aCredentialsProvider) .setRoutePlanner (aRoutePlanner) .setConnectionReuseStrategy (aConnectionReuseStrategy); // Allow gzip,compress aHCB.addInterceptorLast (new RequestAcceptEncoding ()); // Add cookies aHCB.addInterceptorLast (new RequestAddCookies ()); // Un-gzip or uncompress aHCB.addInterceptorLast (new ResponseContentEncoding ()); // Enable usage of Java networking system properties if (m_aSettings.isUseSystemProperties ()) aHCB.useSystemProperties (); // Set retry handler (if needed) if (m_aSettings.hasRetries ()) aHCB.setRetryHandler (createRequestRetryHandler (m_aSettings.getRetryCount (), m_aSettings.getRetryMode ())); // Set user agent (if any) if (m_aSettings.hasUserAgent ()) aHCB.setUserAgent (m_aSettings.getUserAgent ()); return aHCB; } @Nonnull public CloseableHttpClient createHttpClient () { final HttpClientBuilder aBuilder = createHttpClientBuilder (); return aBuilder.build (); } }
apache-2.0
401610239/dialogplus
app/src/main/java/com/orhanobut/android/dialogplussample/MainActivity.java
9756
package com.orhanobut.android.dialogplussample; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.orhanobut.dialogplus.DialogPlus; import com.orhanobut.dialogplus.GridHolder; import com.orhanobut.dialogplus.Holder; import com.orhanobut.dialogplus.ListHolder; import com.orhanobut.dialogplus.OnCancelListener; import com.orhanobut.dialogplus.OnClickListener; import com.orhanobut.dialogplus.OnDismissListener; import com.orhanobut.dialogplus.OnItemClickListener; import com.orhanobut.dialogplus.ViewHolder; public class MainActivity extends ActionBarActivity { private RadioGroup radioGroup; private CheckBox headerCheckBox; private CheckBox footerCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.activity_toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(getString(R.string.app_name)); radioGroup = (RadioGroup) findViewById(R.id.radio_group); headerCheckBox = (CheckBox) findViewById(R.id.header_check_box); footerCheckBox = (CheckBox) findViewById(R.id.footer_check_box); findViewById(R.id.button_bottom).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog( radioGroup.getCheckedRadioButtonId(), DialogPlus.Gravity.BOTTOM, headerCheckBox.isChecked(), footerCheckBox.isChecked() ); } }); findViewById(R.id.button_center).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog( radioGroup.getCheckedRadioButtonId(), DialogPlus.Gravity.CENTER, headerCheckBox.isChecked(), footerCheckBox.isChecked() ); } }); findViewById(R.id.button_top).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog( radioGroup.getCheckedRadioButtonId(), DialogPlus.Gravity.TOP, headerCheckBox.isChecked(), footerCheckBox.isChecked() ); } }); } private void showDialog(int holderId, DialogPlus.Gravity gravity, boolean showHeader, boolean showFooter) { boolean isGrid; Holder holder; switch (holderId) { case R.id.basic_holder_radio_button: holder = new ViewHolder(R.layout.content); isGrid = false; break; case R.id.list_holder_radio_button: holder = new ListHolder(); isGrid = false; break; default: holder = new GridHolder(3); isGrid = true; } OnClickListener clickListener = new OnClickListener() { @Override public void onClick(DialogPlus dialog, View view) { switch (view.getId()) { case R.id.header_container: Toast.makeText(MainActivity.this, "Header clicked", Toast.LENGTH_LONG).show(); break; case R.id.like_it_button: Toast.makeText(MainActivity.this, "We're glad that you like it", Toast.LENGTH_LONG).show(); break; case R.id.love_it_button: Toast.makeText(MainActivity.this, "We're glad that you love it", Toast.LENGTH_LONG).show(); break; case R.id.footer_confirm_button: Toast.makeText(MainActivity.this, "Confirm button clicked", Toast.LENGTH_LONG).show(); break; case R.id.footer_close_button: Toast.makeText(MainActivity.this, "Close button clicked", Toast.LENGTH_LONG).show(); break; } dialog.dismiss(); } }; OnItemClickListener itemClickListener = new OnItemClickListener() { @Override public void onItemClick(DialogPlus dialog, Object item, View view, int position) { TextView textView = (TextView) view.findViewById(R.id.text_view); String clickedAppName = textView.getText().toString(); dialog.dismiss(); Toast.makeText(MainActivity.this, clickedAppName + " clicked", Toast.LENGTH_LONG).show(); } }; OnDismissListener dismissListener = new OnDismissListener() { @Override public void onDismiss(DialogPlus dialog) { Toast.makeText(MainActivity.this, "dismiss listener invoked!", Toast.LENGTH_SHORT).show(); } }; OnCancelListener cancelListener = new OnCancelListener() { @Override public void onCancel(DialogPlus dialog) { Toast.makeText(MainActivity.this, "cancel listener invoked!", Toast.LENGTH_SHORT).show(); } }; SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, isGrid); if (showHeader && showFooter) { showCompleteDialog(holder, gravity, adapter, clickListener, itemClickListener, dismissListener, cancelListener); return; } if (showHeader && !showFooter) { showNoFooterDialog(holder, gravity, adapter, clickListener, itemClickListener, dismissListener, cancelListener); return; } if (!showHeader && showFooter) { showNoHeaderDialog(holder, gravity, adapter, clickListener, itemClickListener, dismissListener, cancelListener); return; } showOnlyContentDialog(holder, gravity, adapter, itemClickListener, dismissListener, cancelListener); } private void showCompleteDialog(Holder holder, DialogPlus.Gravity gravity, BaseAdapter adapter, OnClickListener clickListener, OnItemClickListener itemClickListener, OnDismissListener dismissListener, OnCancelListener cancelListener) { final DialogPlus dialog = new DialogPlus.Builder(this) .setContentHolder(holder) .setHeader(R.layout.header) .setFooter(R.layout.footer) .setCancelable(true) .setGravity(gravity) .setAdapter(adapter) .setOnClickListener(clickListener) .setOnItemClickListener(itemClickListener) .setOnDismissListener(dismissListener) .setOnCancelListener(cancelListener) .create(); dialog.show(); } private void showNoFooterDialog(Holder holder, DialogPlus.Gravity gravity, BaseAdapter adapter, OnClickListener clickListener, OnItemClickListener itemClickListener, OnDismissListener dismissListener, OnCancelListener cancelListener) { final DialogPlus dialog = new DialogPlus.Builder(this) .setContentHolder(holder) .setHeader(R.layout.header) .setCancelable(true) .setGravity(gravity) .setAdapter(adapter) .setOnClickListener(clickListener) .setOnItemClickListener(itemClickListener) .setOnDismissListener(dismissListener) .setOnCancelListener(cancelListener) .create(); dialog.show(); } private void showNoHeaderDialog(Holder holder, DialogPlus.Gravity gravity, BaseAdapter adapter, OnClickListener clickListener, OnItemClickListener itemClickListener, OnDismissListener dismissListener, OnCancelListener cancelListener) { final DialogPlus dialog = new DialogPlus.Builder(this) .setContentHolder(holder) .setFooter(R.layout.footer) .setCancelable(true) .setGravity(gravity) .setAdapter(adapter) .setOnClickListener(clickListener) .setOnItemClickListener(itemClickListener) .setOnDismissListener(dismissListener) .setOnCancelListener(cancelListener) .create(); dialog.show(); } private void showOnlyContentDialog(Holder holder, DialogPlus.Gravity gravity, BaseAdapter adapter, OnItemClickListener itemClickListener, OnDismissListener dismissListener, OnCancelListener cancelListener) { final DialogPlus dialog = new DialogPlus.Builder(this) .setContentHolder(holder) .setCancelable(true) .setGravity(gravity) .setAdapter(adapter) .setOnItemClickListener(itemClickListener) .setOnDismissListener(dismissListener) .setOnCancelListener(cancelListener) .create(); dialog.show(); } }
apache-2.0
mesosphere/usergrid
stack/core/src/main/java/org/apache/usergrid/mq/QueueManager.java
5344
/* * 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.usergrid.mq; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.usergrid.persistence.CounterResolution; import org.apache.usergrid.persistence.Results; import org.apache.usergrid.persistence.exceptions.TransactionNotFoundException; public interface QueueManager { public Queue getQueue( String queuePath ); public Queue updateQueue( String queuePath, Map<String, Object> properties ); public Queue updateQueue( String queuePath, Queue queue ); public Message postToQueue( String queuePath, Message message ); public List<Message> postToQueue( String queuePath, List<Message> messages ); public QueueResults getFromQueue( String queuePath, QueueQuery query ); public Message getMessage( UUID messageId ); public UUID getNewConsumerId(); public QueueSet getQueues( String firstQueuePath, int limit ); public QueueSet subscribeToQueue( String publisherQueuePath, String subscriberQueuePath ); public QueueSet unsubscribeFromQueue( String publisherQueuePath, String subscriberQueuePath ); public QueueSet addSubscribersToQueue( String publisherQueuePath, List<String> subscriberQueuePaths ); public QueueSet removeSubscribersFromQueue( String publisherQueuePath, List<String> subscriberQueuePaths ); public QueueSet subscribeToQueues( String subscriberQueuePath, List<String> publisherQueuePaths ); public QueueSet unsubscribeFromQueues( String subscriberQueuePath, List<String> publisherQueuePaths ); public QueueSet getSubscribers( String publisherQueuePath, String firstSubscriberQueuePath, int limit ); public QueueSet getSubscriptions( String subscriberQueuePath, String firstSubscriptionQueuePath, int limit ); public QueueSet searchSubscribers( String publisherQueuePath, Query query ); public QueueSet getChildQueues( String publisherQueuePath, String firstQueuePath, int count ); public void incrementAggregateQueueCounters( String queuePath, String category, String counterName, long value ); public Results getAggregateQueueCounters( String queuePath, String category, String counterName, CounterResolution resolution, long start, long finish, boolean pad ); public Results getAggregateQueueCounters( String queuePath, CounterQuery query ) throws Exception; public Set<String> getQueueCounterNames( String queuePath ) throws Exception; public void incrementQueueCounters( String queuePath, Map<String, Long> counts ); public void incrementQueueCounter( String queuePath, String name, long value ); public Map<String, Long> getQueueCounters( String queuePath ) throws Exception; /** * Renew a transaction. Will remove the current transaction and return a new one * * @param queuePath The path to the queue * @param transactionId The transaction id */ public UUID renewTransaction( String queuePath, UUID transactionId, QueueQuery query ) throws TransactionNotFoundException; /** * Deletes the transaction for the consumer. Synonymous with "commit." * * @param queuePath The path to the queue * @param transactionId The transaction id * * @see #commitTransaction(String, java.util.UUID, QueueQuery) */ public void deleteTransaction( String queuePath, UUID transactionId, QueueQuery query ); /** * Commits the Transaction for the consumer. * * @param queuePath The path to the queue * @param transactionId The transaction id */ public void commitTransaction( String queuePath, UUID transactionId, QueueQuery query ); /** * Determines if there are any outstanding transactions on a queue * * @param queuePath The path to the queue * @param consumerId The consumer id */ public boolean hasOutstandingTransactions( String queuePath, UUID consumerId ); /** * Determines if there are any Messages to retrieve in a queue. DOES NOT INCLUDE TRANSACTIONS! If you've tried and * failed to process a transaction on the last message in the queue, this will return false * * @param queuePath The path to the queue * @param consumerId The consumer id */ public boolean hasMessagesInQueue( String queuePath, UUID consumerId ); /** Returns true if there are messages waiting to be consumed or pending transactions */ public boolean hasPendingReads( String queuePath, UUID consumerId ); }
apache-2.0
cc-rock/mvp_dagger_example
app/src/main/java/com/ccrock/example/mvp/presenters/BookSearchPresenter.java
2782
package com.ccrock.example.mvp.presenters; import android.util.Log; import com.ccrock.example.mvp.model.Book; import com.ccrock.example.mvp.model.BookList; import com.ccrock.example.mvp.model.BookWrapper; import com.ccrock.example.mvp.model.GoogleBooksApi; import com.ccrock.example.mvp.views.BookSearchView; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import rx.Scheduler; import rx.Subscription; import rx.functions.Action1; /** * Created by carlo on 03/02/2016. */ public class BookSearchPresenter extends MvpPresenter<BookSearchView> { @Inject protected GoogleBooksApi api; @Inject @Named("io") protected Scheduler ioScheduler; @Inject @Named("mainThread") protected Scheduler mainThreadScheduler; private Subscription apiCall; private List<Book> lastResults; @Override protected void initialiseView(BookSearchView view) { if (lastResults != null) { view.hideLoading(); view.showResults(lastResults); } } public void doSearch(String query) { if (isViewAttached()) { getView().showLoading(); lastResults = null; if (apiCall != null) { apiCall.unsubscribe(); } apiCall = api.searchBooks(query) .subscribeOn(ioScheduler) .observeOn(mainThreadScheduler) .subscribe(new Action1<BookList>() { @Override public void call(final BookList bookList) { whenViewAttached(new OnViewAttachedAction<BookSearchView>() { @Override public void execute(BookSearchView view) { view.hideLoading(); List<Book> results = new ArrayList<Book>(bookList.getTotalItems()); for (BookWrapper wrapper : bookList.getItems()) { results.add(wrapper.getVolumeInfo()); } view.showResults(results); lastResults = results; } }); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { // to do: define view.showError and show an error message Log.d("Book_api_call", throwable.getMessage(), throwable); } }); } } }
apache-2.0
NLeSC/vbrowser
source/nl.esciencecenter.glite.lfc/src/nl/esciencecenter/glite/lfc/main/LfcStat.java
1105
/* * Copyrighted 2012-2013 Netherlands eScience Center. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache License at the following location: * 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. * * For the full license, see: LICENCE.txt (located in the root folder of this distribution). * --- */ // source: package nl.esciencecenter.glite.lfc.main; /** * Wrapper for 'lfcls' command. * All LFC commands are in LfcCommand. * * @author P.T de Boer */ public class LfcStat { public static void main(String args[]) { LfcCommand.doSTAT(args); } }
apache-2.0
Anchorer/Lib_dayi
DayiLib/src/main/java/im/dayi/app/library/view/imagecropper/cropwindow/edge/Edge.java
19846
/* * Copyright 2013, Edmodo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or 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 im.dayi.app.library.view.imagecropper.cropwindow.edge; import android.graphics.Rect; import android.view.View; import im.dayi.app.library.view.imagecropper.util.AspectRatioUtil; /** * Enum representing an edge in the crop window. */ public enum Edge { LEFT, TOP, RIGHT, BOTTOM; // Private Constants /////////////////////////////////////////////////////// // Minimum distance in pixels that one edge can get to its opposing edge. // This is an arbitrary value that simply prevents the crop window from // becoming too small. public static final int MIN_CROP_LENGTH_PX = 40; // Member Variables //////////////////////////////////////////////////////// private float mCoordinate; // Public Methods ////////////////////////////////////////////////////////// /** * Sets the coordinate of the Edge. The coordinate will represent the * x-coordinate for LEFT and RIGHT Edges and the y-coordinate for TOP and * BOTTOM edges. * * @param coordinate the position of the edge */ public void setCoordinate(float coordinate) { mCoordinate = coordinate; } /** * Add the given number of pixels to the current coordinate position of this * Edge. * * @param distance the number of pixels to add */ public void offset(float distance) { mCoordinate += distance; } /** * Gets the coordinate of the Edge * * @return the Edge coordinate (x-coordinate for LEFT and RIGHT Edges and * the y-coordinate for TOP and BOTTOM edges) */ public float getCoordinate() { return mCoordinate; } /** * Sets the Edge to the given x-y coordinate but also adjusting for snapping * to the image bounds and parent view border constraints. * * @param x the x-coordinate * @param y the y-coordinate * @param imageRect the bounding rectangle of the image * @param imageSnapRadius the radius (in pixels) at which the edge should * snap to the image */ public void adjustCoordinate(float x, float y, Rect imageRect, float imageSnapRadius, float aspectRatio) { switch (this) { case LEFT: mCoordinate = adjustLeft(x, imageRect, imageSnapRadius, aspectRatio); break; case TOP: mCoordinate = adjustTop(y, imageRect, imageSnapRadius, aspectRatio); break; case RIGHT: mCoordinate = adjustRight(x, imageRect, imageSnapRadius, aspectRatio); break; case BOTTOM: mCoordinate = adjustBottom(y, imageRect, imageSnapRadius, aspectRatio); break; } } /** * Adjusts this Edge position such that the resulting window will have the * given aspect ratio. * * @param aspectRatio the aspect ratio to achieve */ public void adjustCoordinate(float aspectRatio) { final float left = Edge.LEFT.getCoordinate(); final float top = Edge.TOP.getCoordinate(); final float right = Edge.RIGHT.getCoordinate(); final float bottom = Edge.BOTTOM.getCoordinate(); switch (this) { case LEFT: mCoordinate = AspectRatioUtil.calculateLeft(top, right, bottom, aspectRatio); break; case TOP: mCoordinate = AspectRatioUtil.calculateTop(left, right, bottom, aspectRatio); break; case RIGHT: mCoordinate = AspectRatioUtil.calculateRight(left, top, bottom, aspectRatio); break; case BOTTOM: mCoordinate = AspectRatioUtil.calculateBottom(left, top, right, aspectRatio); break; } } /** * Returns whether or not you can re-scale the image based on whether any edge would be out of bounds. * Checks all the edges for a possibility of jumping out of bounds. * * @param edge the Edge that is about to be expanded * @param imageRect the rectangle of the picture * @param aspectRatio the desired aspectRatio of the picture. * * @return whether or not the new image would be out of bounds. */ public boolean isNewRectangleOutOfBounds(Edge edge, Rect imageRect, float aspectRatio) { float offset = edge.snapOffset(imageRect); switch (this) { case LEFT: if (edge.equals(Edge.TOP)) { float top = imageRect.top; float bottom = Edge.BOTTOM.getCoordinate() - offset; float right = Edge.RIGHT.getCoordinate(); float left = AspectRatioUtil.calculateLeft(top, right, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } else if (edge.equals(Edge.BOTTOM)) { float bottom = imageRect.bottom; float top = Edge.TOP.getCoordinate() - offset; float right = Edge.RIGHT.getCoordinate(); float left = AspectRatioUtil.calculateLeft(top, right, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } break; case TOP: if (edge.equals(Edge.LEFT)) { float left = imageRect.left; float right = Edge.RIGHT.getCoordinate() - offset; float bottom = Edge.BOTTOM.getCoordinate(); float top = AspectRatioUtil.calculateTop(left, right, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } else if (edge.equals(Edge.RIGHT)) { float right = imageRect.right; float left = Edge.LEFT.getCoordinate() - offset; float bottom = Edge.BOTTOM.getCoordinate(); float top = AspectRatioUtil.calculateTop(left, right, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } break; case RIGHT: if (edge.equals(Edge.TOP)) { float top = imageRect.top; float bottom = Edge.BOTTOM.getCoordinate() - offset; float left = Edge.LEFT.getCoordinate(); float right = AspectRatioUtil.calculateRight(left, top, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } else if (edge.equals(Edge.BOTTOM)) { float bottom = imageRect.bottom; float top = Edge.TOP.getCoordinate() - offset; float left = Edge.LEFT.getCoordinate(); float right = AspectRatioUtil.calculateRight(left, top, bottom, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } break; case BOTTOM: if (edge.equals(Edge.LEFT)) { float left = imageRect.left; float right = Edge.RIGHT.getCoordinate() - offset; float top = Edge.TOP.getCoordinate(); float bottom = AspectRatioUtil.calculateBottom(left, top, right, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } else if (edge.equals(Edge.RIGHT)) { float right = imageRect.right; float left = Edge.LEFT.getCoordinate() - offset; float top = Edge.TOP.getCoordinate(); float bottom = AspectRatioUtil.calculateBottom(left, top, right, aspectRatio); return isOutOfBounds(top, left, bottom, right, imageRect); } break; } return true; } /** * Returns whether the new rectangle would be out of bounds. * * @param top * @param left * @param bottom * @param right * @param imageRect the Image to be compared with. * @return whether it would be out of bounds */ private boolean isOutOfBounds(float top, float left, float bottom, float right, Rect imageRect) { return (top < imageRect.top || left < imageRect.left || bottom > imageRect.bottom || right > imageRect.right); } /** * Snap this Edge to the given image boundaries. * * @param imageRect the bounding rectangle of the image to snap to * @return the amount (in pixels) that this coordinate was changed (i.e. the * new coordinate minus the old coordinate value) */ public float snapToRect(Rect imageRect) { final float oldCoordinate = mCoordinate; switch (this) { case LEFT: mCoordinate = imageRect.left; break; case TOP: mCoordinate = imageRect.top; break; case RIGHT: mCoordinate = imageRect.right; break; case BOTTOM: mCoordinate = imageRect.bottom; break; } final float offset = mCoordinate - oldCoordinate; return offset; } /** * Returns the potential snap offset of snaptoRect, without changing the coordinate. * * @param imageRect the bounding rectangle of the image to snap to * @return the amount (in pixels) that this coordinate was changed (i.e. the * new coordinate minus the old coordinate value) */ public float snapOffset(Rect imageRect) { final float oldCoordinate = mCoordinate; float newCoordinate = oldCoordinate; switch (this) { case LEFT: newCoordinate = imageRect.left; break; case TOP: newCoordinate = imageRect.top; break; case RIGHT: newCoordinate = imageRect.right; break; case BOTTOM: newCoordinate = imageRect.bottom; break; } final float offset = newCoordinate - oldCoordinate; return offset; } /** * Snap this Edge to the given View boundaries. * * @param view the View to snap to */ public void snapToView(View view) { switch (this) { case LEFT: mCoordinate = 0; break; case TOP: mCoordinate = 0; break; case RIGHT: mCoordinate = view.getWidth(); break; case BOTTOM: mCoordinate = view.getHeight(); break; } } /** * Gets the current width of the crop window. */ public static float getWidth() { return Edge.RIGHT.getCoordinate() - Edge.LEFT.getCoordinate(); } /** * Gets the current height of the crop window. */ public static float getHeight() { return Edge.BOTTOM.getCoordinate() - Edge.TOP.getCoordinate(); } /** * Determines if this Edge is outside the inner margins of the given bounding * rectangle. The margins come inside the actual frame by SNAPRADIUS amount; * therefore, determines if the point is outside the inner "margin" frame. * */ public boolean isOutsideMargin(Rect rect, float margin) { boolean result = false; switch (this) { case LEFT: result = mCoordinate - rect.left < margin; break; case TOP: result = mCoordinate - rect.top < margin; break; case RIGHT: result = rect.right - mCoordinate < margin; break; case BOTTOM: result = rect.bottom - mCoordinate < margin; break; } return result; } /** * Determines if this Edge is outside the image frame of the given bounding * rectangle. */ public boolean isOutsideFrame(Rect rect) { double margin = 0; boolean result = false; switch (this) { case LEFT: result = mCoordinate - rect.left < margin; break; case TOP: result = mCoordinate - rect.top < margin; break; case RIGHT: result = rect.right - mCoordinate < margin; break; case BOTTOM: result = rect.bottom - mCoordinate < margin; break; } return result; } // Private Methods ///////////////////////////////////////////////////////// /** * Get the resulting x-position of the left edge of the crop window given * the handle's position and the image's bounding box and snap radius. * * @param x the x-position that the left edge is dragged to * @param imageRect the bounding box of the image that is being cropped * @param imageSnapRadius the snap distance to the image edge (in pixels) * @return the actual x-position of the left edge */ private static float adjustLeft(float x, Rect imageRect, float imageSnapRadius, float aspectRatio) { float resultX = x; if (x - imageRect.left < imageSnapRadius) resultX = imageRect.left; else { // Select the minimum of the three possible values to use float resultXHoriz = Float.POSITIVE_INFINITY; float resultXVert = Float.POSITIVE_INFINITY; // Checks if the window is too small horizontally if (x >= Edge.RIGHT.getCoordinate() - MIN_CROP_LENGTH_PX) resultXHoriz = Edge.RIGHT.getCoordinate() - MIN_CROP_LENGTH_PX; // Checks if the window is too small vertically if (((Edge.RIGHT.getCoordinate() - x) / aspectRatio) <= MIN_CROP_LENGTH_PX) resultXVert = Edge.RIGHT.getCoordinate() - (MIN_CROP_LENGTH_PX * aspectRatio); resultX = Math.min(resultX, Math.min(resultXHoriz, resultXVert)); } return resultX; } /** * Get the resulting x-position of the right edge of the crop window given * the handle's position and the image's bounding box and snap radius. * * @param x the x-position that the right edge is dragged to * @param imageRect the bounding box of the image that is being cropped * @param imageSnapRadius the snap distance to the image edge (in pixels) * @return the actual x-position of the right edge */ private static float adjustRight(float x, Rect imageRect, float imageSnapRadius, float aspectRatio) { float resultX = x; // If close to the edge if (imageRect.right - x < imageSnapRadius) resultX = imageRect.right; else { // Select the maximum of the three possible values to use float resultXHoriz = Float.NEGATIVE_INFINITY; float resultXVert = Float.NEGATIVE_INFINITY; // Checks if the window is too small horizontally if (x <= Edge.LEFT.getCoordinate() + MIN_CROP_LENGTH_PX) resultXHoriz = Edge.LEFT.getCoordinate() + MIN_CROP_LENGTH_PX; // Checks if the window is too small vertically if (((x - Edge.LEFT.getCoordinate()) / aspectRatio) <= MIN_CROP_LENGTH_PX) { resultXVert = Edge.LEFT.getCoordinate() + (MIN_CROP_LENGTH_PX * aspectRatio); } resultX = Math.max(resultX, Math.max(resultXHoriz, resultXVert)); } return resultX; } /** * Get the resulting y-position of the top edge of the crop window given the * handle's position and the image's bounding box and snap radius. * * @param y the x-position that the top edge is dragged to * @param imageRect the bounding box of the image that is being cropped * @param imageSnapRadius the snap distance to the image edge (in pixels) * @return the actual y-position of the top edge */ private static float adjustTop(float y, Rect imageRect, float imageSnapRadius, float aspectRatio) { float resultY = y; if (y - imageRect.top < imageSnapRadius) resultY = imageRect.top; else { // Select the minimum of the three possible values to use float resultYVert = Float.POSITIVE_INFINITY; float resultYHoriz = Float.POSITIVE_INFINITY; // Checks if the window is too small vertically if (y >= Edge.BOTTOM.getCoordinate() - MIN_CROP_LENGTH_PX) resultYHoriz = Edge.BOTTOM.getCoordinate() - MIN_CROP_LENGTH_PX; // Checks if the window is too small horizontally if (((Edge.BOTTOM.getCoordinate() - y) * aspectRatio) <= MIN_CROP_LENGTH_PX) resultYVert = Edge.BOTTOM.getCoordinate() - (MIN_CROP_LENGTH_PX / aspectRatio); resultY = Math.min(resultY, Math.min(resultYHoriz, resultYVert)); } return resultY; } /** * Get the resulting y-position of the bottom edge of the crop window given * the handle's position and the image's bounding box and snap radius. * * @param y the x-position that the bottom edge is dragged to * @param imageRect the bounding box of the image that is being cropped * @param imageSnapRadius the snap distance to the image edge (in pixels) * @return the actual y-position of the bottom edge */ private static float adjustBottom(float y, Rect imageRect, float imageSnapRadius, float aspectRatio) { float resultY = y; if (imageRect.bottom - y < imageSnapRadius) resultY = imageRect.bottom; else { // Select the maximum of the three possible values to use float resultYVert = Float.NEGATIVE_INFINITY; float resultYHoriz = Float.NEGATIVE_INFINITY; // Checks if the window is too small vertically if (y <= Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX) resultYVert = Edge.TOP.getCoordinate() + MIN_CROP_LENGTH_PX; // Checks if the window is too small horizontally if (((y - Edge.TOP.getCoordinate()) * aspectRatio) <= MIN_CROP_LENGTH_PX) resultYHoriz = Edge.TOP.getCoordinate() + (MIN_CROP_LENGTH_PX / aspectRatio); resultY = Math.max(resultY, Math.max(resultYHoriz, resultYVert)); } return resultY; } }
apache-2.0
mmm2a/GridApp
test/com/morgan/grid/server/common/feature/AllFeatureTests.java
334
package com.morgan.grid.server.common.feature; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ DisabledFeaturePredicateParserTest.class, FeatureFileTest.class, ServerFeatureCheckerTest.class }) public class AllFeatureTests { }
apache-2.0
dremio/dremio-oss
services/namespace/src/main/java/com/dremio/service/namespace/PartitionChunkSerializer.java
1025
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.service.namespace; import com.dremio.datastore.LegacyProtobufSerializer; import com.dremio.service.namespace.dataset.proto.PartitionProtobuf.PartitionChunk; /** * A serializer for partition chunks. */ public class PartitionChunkSerializer extends LegacyProtobufSerializer<PartitionChunk> { public PartitionChunkSerializer() { super(PartitionChunk.class, PartitionChunk.PARSER); } }
apache-2.0
tangxin983/archetype
src/main/java/com/github/tx/archetype/modules/tag/Functions.java
346
package com.github.tx.archetype.modules.tag; import java.util.Collection; /** * 自定义函数标签对应类 * * @author tangx * */ public class Functions { public static <T> boolean contains(Collection<T> coll, Object o) { if (coll != null && !coll.isEmpty()) { return coll.contains(o); } else { return false; } } }
apache-2.0
aliyun-beta/aliyun-oss-hadoop-fs
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/tools/TestCLI.java
6933
/** * 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.hadoop.mapreduce.tools; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Cluster; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.TaskReport; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.JobPriority; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.JobStatus.State; import org.apache.hadoop.util.Time; import org.junit.Assert; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.doReturn; public class TestCLI { private static String jobIdStr = "job_1015298225799_0015"; @Test public void testListAttemptIdsWithValidInput() throws Exception { JobID jobId = JobID.forName(jobIdStr); Cluster mockCluster = mock(Cluster.class); Job job = mock(Job.class); CLI cli = spy(new CLI(new Configuration())); doReturn(mockCluster).when(cli).createCluster(); when(job.getTaskReports(TaskType.MAP)).thenReturn( getTaskReports(jobId, TaskType.MAP)); when(job.getTaskReports(TaskType.REDUCE)).thenReturn( getTaskReports(jobId, TaskType.REDUCE)); when(mockCluster.getJob(jobId)).thenReturn(job); int retCode_MAP = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "MAP", "running" }); // testing case insensitive behavior int retCode_map = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "map", "running" }); int retCode_REDUCE = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "REDUCE", "running" }); int retCode_completed = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "REDUCE", "completed" }); assertEquals("MAP is a valid input,exit code should be 0", 0, retCode_MAP); assertEquals("map is a valid input,exit code should be 0", 0, retCode_map); assertEquals("REDUCE is a valid input,exit code should be 0", 0, retCode_REDUCE); assertEquals( "REDUCE and completed are a valid inputs to -list-attempt-ids,exit code should be 0", 0, retCode_completed); verify(job, times(2)).getTaskReports(TaskType.MAP); verify(job, times(2)).getTaskReports(TaskType.REDUCE); } @Test public void testListAttemptIdsWithInvalidInputs() throws Exception { JobID jobId = JobID.forName(jobIdStr); Cluster mockCluster = mock(Cluster.class); Job job = mock(Job.class); CLI cli = spy(new CLI()); doReturn(mockCluster).when(cli).createCluster(); when(mockCluster.getJob(jobId)).thenReturn(job); int retCode_JOB_SETUP = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "JOB_SETUP", "running" }); int retCode_JOB_CLEANUP = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "JOB_CLEANUP", "running" }); int retCode_invalidTaskState = cli.run(new String[] { "-list-attempt-ids", jobIdStr, "REDUCE", "complete" }); assertEquals("JOB_SETUP is an invalid input,exit code should be -1", -1, retCode_JOB_SETUP); assertEquals("JOB_CLEANUP is an invalid input,exit code should be -1", -1, retCode_JOB_CLEANUP); assertEquals("complete is an invalid input,exit code should be -1", -1, retCode_invalidTaskState); } private TaskReport[] getTaskReports(JobID jobId, TaskType type) { return new TaskReport[] { new TaskReport(), new TaskReport() }; } @Test public void testJobKIll() throws Exception { Cluster mockCluster = mock(Cluster.class); CLI cli = spy(new CLI(new Configuration())); doReturn(mockCluster).when(cli).createCluster(); String jobId1 = "job_1234654654_001"; String jobId2 = "job_1234654654_002"; String jobId3 = "job_1234654654_003"; String jobId4 = "job_1234654654_004"; Job mockJob1 = mockJob(mockCluster, jobId1, State.RUNNING); Job mockJob2 = mockJob(mockCluster, jobId2, State.KILLED); Job mockJob3 = mockJob(mockCluster, jobId3, State.FAILED); Job mockJob4 = mockJob(mockCluster, jobId4, State.PREP); int exitCode1 = cli.run(new String[] { "-kill", jobId1 }); assertEquals(0, exitCode1); verify(mockJob1, times(1)).killJob(); int exitCode2 = cli.run(new String[] { "-kill", jobId2 }); assertEquals(-1, exitCode2); verify(mockJob2, times(0)).killJob(); int exitCode3 = cli.run(new String[] { "-kill", jobId3 }); assertEquals(-1, exitCode3); verify(mockJob3, times(0)).killJob(); int exitCode4 = cli.run(new String[] { "-kill", jobId4 }); assertEquals(0, exitCode4); verify(mockJob4, times(1)).killJob(); } private Job mockJob(Cluster mockCluster, String jobId, State jobState) throws IOException, InterruptedException { Job mockJob = mock(Job.class); when(mockCluster.getJob(JobID.forName(jobId))).thenReturn(mockJob); JobStatus status = new JobStatus(null, 0, 0, 0, 0, jobState, JobPriority.HIGH, null, null, null, null); when(mockJob.getStatus()).thenReturn(status); return mockJob; } @Test public void testGetJob() throws Exception { Configuration conf = new Configuration(); long sleepTime = 100; conf.setLong(MRJobConfig.MR_CLIENT_JOB_RETRY_INTERVAL, sleepTime); Cluster mockCluster = mock(Cluster.class); JobID jobId1 = JobID.forName("job_1234654654_001"); when(mockCluster.getJob(jobId1)).thenReturn(null); for (int i = 0; i < 2; ++i) { conf.setInt(MRJobConfig.MR_CLIENT_JOB_MAX_RETRIES, i); CLI cli = spy(new CLI(conf)); cli.cluster = mockCluster; doReturn(mockCluster).when(cli).createCluster(); long start = Time.monotonicNow(); cli.getJob(jobId1); long end = Time.monotonicNow(); Assert.assertTrue(end - start > (i * sleepTime)); Assert.assertTrue(end - start < ((i + 1) * sleepTime)); } } }
apache-2.0
efortuna/AndroidSDKClone
ndk_experimental/samples/MoreTeapots/src/com/sample/moreteapots/MoreTeapotsApplication.java
1731
/* * Copyright 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sample.moreteapots; import javax.microedition.khronos.opengles.GL10; import com.sample.helper.NDKHelper; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.opengl.GLUtils; import android.util.Log; import android.widget.Toast; public class MoreTeapotsApplication extends Application { public void onCreate(){ Log.w("native-activity", "onCreate"); final PackageManager pm = getApplicationContext().getPackageManager(); ApplicationInfo ai; try { ai = pm.getApplicationInfo( this.getPackageName(), 0); } catch (final NameNotFoundException e) { ai = null; } final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)"); Toast.makeText(this, applicationName, Toast.LENGTH_SHORT).show(); } }
apache-2.0
kydiwen/C24detector
app/src/main/java/com/okq/C24detector/Utils/mprintUtils.java
3843
package com.okq.C24detector.Utils; import com.kydiwen.easyserial.Utils.StringOrHex; import com.kydiwen.easyserial.Utils.exclusiveUtils; import java.io.UnsupportedEncodingException; /** * Created by 孙文权 on 2016/12/20. * 数据打印字符转换类 */ public class mprintUtils{ /** * @param data 需要打印的数据 * @param count 当前打印数据的条数 */ public static String print(String data, int count){ String printString; StringBuilder builder = null; String hexString = "0123456789ABCDEF"; try{ try{ byte[] bytes = data.getBytes("GBK"); int e = bytes.length; builder = new StringBuilder(e * 2); for(int i = 0; i < e; ++ i){ builder.append(hexString.charAt((bytes[i] & 240) >> 4)); builder.append(hexString.charAt((bytes[i] & 15) >> 0)); } }catch(UnsupportedEncodingException var5){ var5.printStackTrace(); } builder.append("0A"); printString = "0327" + StringOrHex.intTohexstring(count) + StringOrHex.intTohexstring(builder.toString() .length() / 2) + builder.toString(); return getPasswayOrder("03", printString.substring(2)); }catch(Exception e){ e.printStackTrace(); } return null; } //进行异或转换,得到十六进制命令 private static String getPasswayOrder(String string1, String string2){ String result = string1; for(int i = 0; i < string2.length(); i += 2){ result = exclusiveUtils.xor(result, string2.substring(i, i + 2)); } return string1 + string2 + result; } public static String encodeCN(String data){ String hexString = "0123456789ABCDEF"; byte[] bytes; try{ bytes = data.getBytes("UTF-8"); StringBuilder sb = new StringBuilder(bytes.length * 2); for(int i = 0; i < bytes.length; i++){ sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4)); sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)); } return sb.toString(); }catch(UnsupportedEncodingException e){ e.printStackTrace(); } return ""; } /** * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名. * * @param s 原串 * @return */ public static String convertStringToUTF8(String s){ if(s == null || s.equals("")){ return null; } StringBuffer sb = new StringBuffer(); try{ char c; for(int i = 0; i < s.length(); i++){ c = s.charAt(i); if(c >= 0 && c <= 255){ sb.append(c); }else{ byte[] b; b = Character.toString(c) .getBytes("utf-8"); for(int j = 0; j < b.length; j++){ int k = b[j]; if(k < 0){ k += 256; } sb.append(Integer.toHexString(k) .toUpperCase()); // sb.append("%" +Integer.toHexString(k).toUpperCase()); } } } }catch(Exception e){ e.printStackTrace(); } return sb.toString(); } }
apache-2.0
JetBrains/xodus
utils/src/test/java/jetbrains/exodus/core/dataStructures/persistent/PersistentHashMapTest.java
7338
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.core.dataStructures.persistent; import jetbrains.exodus.util.Random; import org.junit.Assert; import org.junit.Test; public class PersistentHashMapTest { private static final int ENTRIES_TO_ADD = 5000; @Test public void mutableTreeRandomInsertDeleteTest() { Random random = new Random(2343489); PersistentHashMap<Integer, String> map = new PersistentHashMap<>(); checkInsertRemove(random, map, 100); checkInsertRemove(random, map, ENTRIES_TO_ADD); for (int i = 0; i < 100; i++) { checkInsertRemove(random, map, 100); } } @Test public void hashKeyCollision() { final PersistentHashMap<HashKey, String> map = new PersistentHashMap<>(); PersistentHashMap<HashKey, String>.MutablePersistentHashMap w = map.beginWrite(); HashKey first = new HashKey(1); w.put(first, "a"); HashKey second = new HashKey(1); w.put(second, "b"); w.endWrite(); Assert.assertEquals(2, map.getCurrent().size()); w = map.beginWrite(); w.removeKey(first); w.endWrite(); Assert.assertEquals(1, map.getCurrent().size()); } @SuppressWarnings({"OverlyLongMethod"}) @Test public void competingWritesTest() { PersistentHashMap<Integer, String> tree = new PersistentHashMap<>(); PersistentHashMap<Integer, String>.MutablePersistentHashMap write1 = tree.beginWrite(); PersistentHashMap<Integer, String>.MutablePersistentHashMap write2 = tree.beginWrite(); write1.put(0, "0"); write2.removeKey(1); Assert.assertTrue(write2.endWrite()); Assert.assertTrue(write1.endWrite()); PersistentHashMap<Integer, String>.ImmutablePersistentHashMap read = tree.getCurrent(); Assert.assertTrue(read.containsKey(0)); Assert.assertFalse(read.containsKey(1)); Assert.assertFalse(read.containsKey(2)); Assert.assertFalse(read.containsKey(3)); Assert.assertEquals(1, read.size()); write1.put(2, "2"); write2.put(3, "3"); Assert.assertTrue(write1.endWrite()); Assert.assertFalse(write2.endWrite()); Assert.assertTrue(read.containsKey(0)); Assert.assertFalse(read.containsKey(1)); Assert.assertFalse(read.containsKey(2)); Assert.assertFalse(read.containsKey(3)); Assert.assertEquals(1, read.size()); read = tree.getCurrent(); Assert.assertTrue(read.containsKey(0)); Assert.assertFalse(read.containsKey(1)); Assert.assertTrue(read.containsKey(2)); Assert.assertFalse(read.containsKey(3)); Assert.assertEquals(2, read.size()); Object root = write1.getRoot(); write1.put(2, "2"); Assert.assertNotSame(write1.getRoot(), root); root = write2.getRoot(); write2.put(2, "_2"); Assert.assertNotSame(write2.getRoot(), root); Assert.assertTrue(write1.endWrite()); Assert.assertFalse(write2.endWrite()); read = tree.getCurrent(); Assert.assertTrue(read.containsKey(0)); Assert.assertFalse(read.containsKey(1)); Assert.assertTrue(read.containsKey(2)); Assert.assertFalse(read.containsKey(3)); Assert.assertEquals(2, read.size()); } @Test public void testOverwrite() { final PersistentHashMap<Integer, String> tree = new PersistentHashMap<>(); PersistentHashMap<Integer, String>.MutablePersistentHashMap mutable = tree.beginWrite(); mutable.put(0, "0"); Assert.assertTrue(mutable.endWrite()); Assert.assertEquals("0", tree.getCurrent().get(0)); mutable = tree.beginWrite(); mutable.put(0, "0.0"); Assert.assertTrue(mutable.endWrite()); Assert.assertEquals("0.0", tree.getCurrent().get(0)); } private static void checkInsertRemove(Random random, PersistentHashMap<Integer, String> map, int count) { PersistentHashMap<Integer, String>.MutablePersistentHashMap write = map.beginWrite(); write.checkTip(); addEntries(random, write, count); removeEntries(random, write, count); Assert.assertEquals(0, write.size()); Assert.assertTrue(write.isEmpty()); Assert.assertTrue(write.endWrite()); } private static void addEntries(Random random, PersistentHashMap<Integer, String>.MutablePersistentHashMap tree, int count) { int[] p = genPermutation(random, count); for (int i = 0; i < count; i++) { int size = tree.size(); Assert.assertEquals(i, size); int key = p[i]; tree.put(key, key + " "); Assert.assertFalse(tree.isEmpty()); tree.checkTip(); Assert.assertEquals(i + 1, tree.size()); tree.put(key, String.valueOf(key)); tree.checkTip(); Assert.assertEquals(i + 1, tree.size()); for (int j = 0; j <= 10; j++) { int testKey = p[i * j / 10]; Assert.assertTrue(tree.containsKey(testKey)); } if (i < count - 1) { Assert.assertFalse(tree.containsKey(p[i + 1])); } } } private static void removeEntries(Random random, PersistentHashMap<Integer, String>.MutablePersistentHashMap tree, int count) { int[] p = genPermutation(random, count); for (int i = 0; i < count; i++) { int size = tree.size(); Assert.assertEquals(count - i, size); Assert.assertFalse(tree.isEmpty()); int key = p[i]; Assert.assertEquals(String.valueOf(key), tree.removeKey(key)); tree.checkTip(); Assert.assertNull(tree.removeKey(key)); tree.checkTip(); for (int j = 0; j <= 10; j++) { int testKey = p[i * j / 10]; Assert.assertFalse(tree.containsKey(testKey)); } if (i < count - 1) { Assert.assertTrue(tree.containsKey(p[i + 1])); } } } private static int[] genPermutation(Random random, int size) { int[] p = new int[size]; for (int i = 1; i < size; i++) { int j = random.nextInt(i); p[i] = p[j]; p[j] = i; } return p; } private class HashKey { private final int hashCode; private HashKey(int hashCode) { this.hashCode = hashCode; } // equals isn't overriden intentionally (default is identity comparison) to emulate hash collision @Override public int hashCode() { return hashCode; } } }
apache-2.0
sbmart/basic_blog
target/.generated/com/google/web/bindery/requestfactory/shared/EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.java
5175
package com.google.web.bindery.requestfactory.shared; public class EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory extends com.google.web.bindery.autobean.shared.impl.AbstractAutoBean<com.google.web.bindery.requestfactory.shared.EntityProxy> { private final com.google.web.bindery.requestfactory.shared.EntityProxy shim = new com.google.web.bindery.requestfactory.shared.EntityProxy() { public com.google.web.bindery.requestfactory.shared.EntityProxyId stableId() { com.google.web.bindery.requestfactory.shared.EntityProxyId toReturn = EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this.getWrapped().stableId(); toReturn = com.google.web.bindery.requestfactory.shared.impl.BaseProxyCategory.__intercept(EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this, toReturn); EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this.call("stableId", toReturn ); return toReturn; } @Override public boolean equals(Object o) { return this == o || getWrapped().equals(o); } @Override public int hashCode() { return getWrapped().hashCode(); } @Override public String toString() { return getWrapped().toString(); } }; { com.google.gwt.core.client.impl.WeakMapping.set(shim, com.google.web.bindery.autobean.shared.AutoBean.class.getName(), this); } public EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory(com.google.web.bindery.autobean.shared.AutoBeanFactory factory) {super(factory);} public EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory(com.google.web.bindery.autobean.shared.AutoBeanFactory factory, com.google.web.bindery.requestfactory.shared.EntityProxy wrapped) { super(wrapped, factory); } public com.google.web.bindery.requestfactory.shared.EntityProxy as() {return shim;} public Class<com.google.web.bindery.requestfactory.shared.EntityProxy> getType() {return com.google.web.bindery.requestfactory.shared.EntityProxy.class;} @Override protected com.google.web.bindery.requestfactory.shared.EntityProxy createSimplePeer() { return new com.google.web.bindery.requestfactory.shared.EntityProxy() { private final com.google.web.bindery.autobean.shared.Splittable data = com.google.web.bindery.requestfactory.shared.EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this.data; public com.google.web.bindery.requestfactory.shared.EntityProxyId stableId() { return com.google.web.bindery.requestfactory.shared.impl.EntityProxyCategory.stableId(EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this); } public boolean equals(java.lang.Object other) { return com.google.web.bindery.requestfactory.shared.impl.EntityProxyCategory.equals(EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this, other); } public int hashCode() { return com.google.web.bindery.requestfactory.shared.impl.EntityProxyCategory.hashCode(EntityProxyAutoBean_com_google_web_bindery_requestfactory_shared_impl_EntityProxyCategory_com_google_web_bindery_requestfactory_shared_impl_ValueProxyCategory_com_google_web_bindery_requestfactory_shared_impl_BaseProxyCategory.this); } }; } @Override protected void traverseProperties(com.google.web.bindery.autobean.shared.AutoBeanVisitor visitor, com.google.web.bindery.autobean.shared.impl.AbstractAutoBean.OneShotContext ctx) { com.google.web.bindery.autobean.shared.impl.AbstractAutoBean bean; Object value; com.google.web.bindery.autobean.gwt.client.impl.ClientPropertyContext propertyContext; com.google.web.bindery.requestfactory.shared.EntityProxy as = as(); } }
apache-2.0
Wizzercn/NutzWk
src/main/java/com/budwk/app/base/page/datatable/DataTableColumn.java
937
package com.budwk.app.base.page.datatable; import java.io.Serializable; /** * Created by wizzer on 2016/6/27. */ public class DataTableColumn implements Serializable { private static final long serialVersionUID = 1L; protected String data; protected String name; protected boolean searchable; protected boolean orderable; public String getData() { return data; } public void setData(String data) { this.data = data; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSearchable() { return searchable; } public void setSearchable(boolean searchable) { this.searchable = searchable; } public boolean isOrderable() { return orderable; } public void setOrderable(boolean orderable) { this.orderable = orderable; } }
apache-2.0
drusak/tabactivity
sample/src/main/java/com/delicacyset/tabactivitysample/fragment/FragmentTab2.java
756
package com.delicacyset.tabactivitysample.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.delicacyset.tabactivity.fragment.BaseTabFragment; import com.delicacyset.tabactivitysample.R; /** * Created by Dmitry Rusak on 12/23/15. * <p/> */ public class FragmentTab2 extends FirstLevelFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tab_2, container, false); } @Override public String getFragmentId() { return this.getClass().getSimpleName(); } }
apache-2.0
kong-kevin/pigweather
src/com/pigweather/app/activity/WeatherActivity.java
5430
package com.pigweather.app.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.pigweather.app.R; import com.pigweather.app.service.AutoUpdateService; import com.pigweather.app.util.HttpCallbackListener; import com.pigweather.app.util.HttpUtil; import com.pigweather.app.util.Utility; public class WeatherActivity extends Activity implements OnClickListener { private LinearLayout weatherInfoLayout; //ÓÃÓÚÏÔʾ³ÇÊÐÃû private TextView cityNameText; //ÓÃÓÚÏÔʾ·¢²¼Ê±¼ä private TextView publishText; //ÓÃÓÚÏÔʾÌìÆøÃèÊöÐÅÏ¢ private TextView weatherDespText; //ÓÃÓÚÏÔÊ¾ÆøÎÂ1 private TextView temp1Text; //ÓÃÓÚÏÔÊ¾ÆøÎÂ2 private TextView temp2Text; //ÓÃÓÚÏÔʾµ±Ç°ÈÕÆÚ private TextView currentDateText; //Çл»³ÇÊа´Å¥ private Button switchCity; //¸üÐÂÌìÆø°´Å¥ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); // ³õʼ»¯¸÷¿Ø¼þ weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout); cityNameText = (TextView) findViewById(R.id.city_name); publishText = (TextView) findViewById(R.id.publish_text); weatherDespText = (TextView) findViewById(R.id.weather_desp); temp1Text = (TextView) findViewById(R.id.temp1); temp2Text = (TextView) findViewById(R.id.temp2); currentDateText = (TextView) findViewById(R.id.current_date); switchCity = (Button) findViewById(R.id.switch_city); refreshWeather = (Button) findViewById(R.id.refresh_weather); switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { // ÓÐÏØ¼¶´úºÅʱ¾ÍÈ¥²éѯÌìÆø publishText.setText("ͬ²½ÖÐ..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { // ûÓÐÏØ¼¶´úºÅʱ¾ÍÖ±½ÓÏÔʾ±¾µØÌìÆø showWeather(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.switch_city: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("ͬ²½ÖÐ..."); SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; default: break; } } /** * ²éÑ¯ÏØ¼¶´úºÅËù¶ÔÓ¦µÄÌìÆø´úºÅ¡£ */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"; queryFromServer(address, "countyCode"); } /** * ²éѯÌìÆø´úºÅËù¶ÔÓ¦µÄÌìÆø¡£ */ private void queryWeatherInfo(String weatherCode) { String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; queryFromServer(address, "weatherCode"); } /** * ¸ù¾Ý´«ÈëµÄµØÖ·ºÍÀàÐÍÈ¥Ïò·þÎñÆ÷²éѯÌìÆø´úºÅ»òÕßÌìÆøÐÅÏ¢¡£ */ private void queryFromServer(final String address, final String type) { HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { // ´Ó·þÎñÆ÷·µ»ØµÄÊý¾ÝÖнâÎö³öÌìÆø´úºÅ String[] array = response.split("\\|"); if (array != null && array.length == 2) { String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if ("weatherCode".equals(type)) { // ´¦Àí·þÎñÆ÷·µ»ØµÄÌìÆøÐÅÏ¢ Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishText.setText("ͬ²½Ê§°Ü"); } }); } }); } /** * ´ÓSharedPreferencesÎļþÖжÁÈ¡´æ´¢µÄÌìÆøÐÅÏ¢£¬²¢ÏÔʾµ½½çÃæÉÏ¡£ */ private void showWeather() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("½ñÌì" + prefs.getString("publish_time", "") + "·¢²¼"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
apache-2.0
jenkinsci/zephyr-enterprise-test-management-plugin
src/main/java/com/thed/model/ReleaseTestSchedule.java
956
package com.thed.model; /** * Created by prashant on 29/6/19. */ public class ReleaseTestSchedule extends BaseEntity { private String status; private Long testerId; private TCRCatalogTreeTestcase tcrTreeTestcase; private Long cyclePhaseId; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getTesterId() { return testerId; } public void setTesterId(Long testerId) { this.testerId = testerId; } public TCRCatalogTreeTestcase getTcrTreeTestcase() { return tcrTreeTestcase; } public void setTcrTreeTestcase(TCRCatalogTreeTestcase tcrTreeTestcase) { this.tcrTreeTestcase = tcrTreeTestcase; } public Long getCyclePhaseId() { return cyclePhaseId; } public void setCyclePhaseId(Long cyclePhaseId) { this.cyclePhaseId = cyclePhaseId; } }
apache-2.0
escidoc-ng/escidoc-ng
escidocng-benchtool/src/main/java/de/escidocng/bench/BenchToolResult.java
1090
/* * Copyright 2014 FIZ Karlsruhe * * 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 ROLE_ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.escidocng.bench; public class BenchToolResult { private final long duration; private final long size; public BenchToolResult(long size, long duration) { this.duration = duration; this.size = size; } public long getSize() { return size; } public float getThroughput() { return ((float) size * 1000f) / ((float) duration * 1024f * 1024f); } public long getDuration() { return duration; } }
apache-2.0
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/layers/mercator/MercatorTiledImageLayer.java
39964
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.layers.mercator; import com.jogamp.opengl.util.awt.TextRenderer; import gov.nasa.worldwind.*; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.globes.Globe; import gov.nasa.worldwind.layers.AbstractLayer; import gov.nasa.worldwind.render.DrawContext; import gov.nasa.worldwind.retrieve.*; import gov.nasa.worldwind.util.*; import javax.imageio.ImageIO; import javax.media.opengl.*; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.List; import java.util.concurrent.PriorityBlockingQueue; /** * TiledImageLayer modified 2009-02-03 to add support for Mercator projections. * * @author tag * @version $Id: MercatorTiledImageLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ public abstract class MercatorTiledImageLayer extends AbstractLayer { // Infrastructure private static final LevelComparer levelComparer = new LevelComparer(); private final LevelSet levels; private ArrayList<MercatorTextureTile> topLevels; private boolean forceLevelZeroLoads = false; private boolean levelZeroLoaded = false; private boolean retainLevelZeroTiles = false; private String tileCountName; @SuppressWarnings({"FieldCanBeLocal"}) private double splitScale = 0.9; // TODO: Make configurable private boolean useMipMaps = false; private ArrayList<String> supportedImageFormats = new ArrayList<String>(); // Diagnostic flags private boolean showImageTileOutlines = false; private boolean drawTileBoundaries = false; private boolean useTransparentTextures = false; private boolean drawTileIDs = false; private boolean drawBoundingVolumes = false; // Stuff computed each frame private ArrayList<MercatorTextureTile> currentTiles = new ArrayList<MercatorTextureTile>(); private MercatorTextureTile currentResourceTile; private Vec4 referencePoint; private boolean atMaxResolution = false; private PriorityBlockingQueue<Runnable> requestQ = new PriorityBlockingQueue<Runnable>( 200); abstract protected void requestTexture(DrawContext dc, MercatorTextureTile tile); abstract protected void forceTextureLoad(MercatorTextureTile tile); public MercatorTiledImageLayer(LevelSet levelSet) { if (levelSet == null) { String message = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.levels = new LevelSet(levelSet); // the caller's levelSet may change internally, so we copy it. this.createTopLevelTiles(); this.setPickEnabled(false); // textures are assumed to be terrain unless specifically indicated otherwise. this.tileCountName = this.getName() + " Tiles"; } @Override public void setName(String name) { super.setName(name); this.tileCountName = this.getName() + " Tiles"; } public boolean isUseTransparentTextures() { return this.useTransparentTextures; } public void setUseTransparentTextures(boolean useTransparentTextures) { this.useTransparentTextures = useTransparentTextures; } public boolean isForceLevelZeroLoads() { return this.forceLevelZeroLoads; } public void setForceLevelZeroLoads(boolean forceLevelZeroLoads) { this.forceLevelZeroLoads = forceLevelZeroLoads; } public boolean isRetainLevelZeroTiles() { return retainLevelZeroTiles; } public void setRetainLevelZeroTiles(boolean retainLevelZeroTiles) { this.retainLevelZeroTiles = retainLevelZeroTiles; } public boolean isDrawTileIDs() { return drawTileIDs; } public void setDrawTileIDs(boolean drawTileIDs) { this.drawTileIDs = drawTileIDs; } public boolean isDrawTileBoundaries() { return drawTileBoundaries; } public void setDrawTileBoundaries(boolean drawTileBoundaries) { this.drawTileBoundaries = drawTileBoundaries; } public boolean isShowImageTileOutlines() { return showImageTileOutlines; } public void setShowImageTileOutlines(boolean showImageTileOutlines) { this.showImageTileOutlines = showImageTileOutlines; } public boolean isDrawBoundingVolumes() { return drawBoundingVolumes; } public void setDrawBoundingVolumes(boolean drawBoundingVolumes) { this.drawBoundingVolumes = drawBoundingVolumes; } protected LevelSet getLevels() { return levels; } protected PriorityBlockingQueue<Runnable> getRequestQ() { return requestQ; } public boolean isMultiResolution() { return this.getLevels() != null && this.getLevels().getNumLevels() > 1; } public boolean isAtMaxResolution() { return this.atMaxResolution; } public boolean isUseMipMaps() { return useMipMaps; } public void setUseMipMaps(boolean useMipMaps) { this.useMipMaps = useMipMaps; } private void createTopLevelTiles() { MercatorSector sector = (MercatorSector) this.levels.getSector(); Level level = levels.getFirstLevel(); Angle dLat = level.getTileDelta().getLatitude(); Angle dLon = level.getTileDelta().getLongitude(); Angle latOrigin = this.levels.getTileOrigin().getLatitude(); Angle lonOrigin = this.levels.getTileOrigin().getLongitude(); // Determine the row and column offset from the common World Wind global tiling origin. int firstRow = Tile.computeRow(dLat, sector.getMinLatitude(), latOrigin); int firstCol = Tile.computeColumn(dLon, sector.getMinLongitude(), lonOrigin); int lastRow = Tile.computeRow(dLat, sector.getMaxLatitude(), latOrigin); int lastCol = Tile.computeColumn(dLon, sector.getMaxLongitude(), lonOrigin); int nLatTiles = lastRow - firstRow + 1; int nLonTiles = lastCol - firstCol + 1; this.topLevels = new ArrayList<MercatorTextureTile>(nLatTiles * nLonTiles); //Angle p1 = Tile.computeRowLatitude(firstRow, dLat); double deltaLat = dLat.degrees / 90; double d1 = -1.0 + deltaLat * firstRow; for (int row = firstRow; row <= lastRow; row++) { //Angle p2; //p2 = p1.add(dLat); double d2 = d1 + deltaLat; Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); for (int col = firstCol; col <= lastCol; col++) { Angle t2; t2 = t1.add(dLon); this.topLevels.add(new MercatorTextureTile(new MercatorSector( d1, d2, t1, t2), level, row, col)); t1 = t2; } d1 = d2; } } private void loadAllTopLevelTextures(DrawContext dc) { for (MercatorTextureTile tile : this.topLevels) { if (!tile.isTextureInMemory(dc.getTextureCache())) this.forceTextureLoad(tile); } this.levelZeroLoaded = true; } // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // private void assembleTiles(DrawContext dc) { this.currentTiles.clear(); for (MercatorTextureTile tile : this.topLevels) { if (this.isTileVisible(dc, tile)) { this.currentResourceTile = null; this.addTileOrDescendants(dc, tile); } } } private void addTileOrDescendants(DrawContext dc, MercatorTextureTile tile) { if (this.meetsRenderCriteria(dc, tile)) { this.addTile(dc, tile); return; } // The incoming tile does not meet the rendering criteria, so it must be subdivided and those // subdivisions tested against the criteria. // All tiles that meet the selection criteria are drawn, but some of those tiles will not have // textures associated with them either because their texture isn't loaded yet or because they // are finer grain than the layer has textures for. In these cases the tiles use the texture of // the closest ancestor that has a texture loaded. This ancestor is called the currentResourceTile. // A texture transform is applied during rendering to align the sector's texture coordinates with the // appropriate region of the ancestor's texture. MercatorTextureTile ancestorResource = null; try { // TODO: Revise this to reflect that the parent layer is only requested while the algorithm continues // to search for the layer matching the criteria. // At this point the tile does not meet the render criteria but it may have its texture in memory. // If so, register this tile as the resource tile. If not, then this tile will be the next level // below a tile with texture in memory. So to provide progressive resolution increase, add this tile // to the draw list. That will cause the tile to be drawn using its parent tile's texture, and it will // cause it's texture to be requested. At some future call to this method the tile's texture will be in // memory, it will not meet the render criteria, but will serve as the parent to a tile that goes // through this same process as this method recurses. The result of all this is that a tile isn't rendered // with its own texture unless all its parents have their textures loaded. In addition to causing // progressive resolution increase, this ensures that the parents are available as the user zooms out, and // therefore the layer remains visible until the user is zoomed out to the point the layer is no longer // active. if (tile.isTextureInMemory(dc.getTextureCache()) || tile.getLevelNumber() == 0) { ancestorResource = this.currentResourceTile; this.currentResourceTile = tile; } else if (!tile.getLevel().isEmpty()) { // this.addTile(dc, tile); // return; // Issue a request for the parent before descending to the children. if (tile.getLevelNumber() < this.levels.getNumLevels()) { // Request only tiles with data associated at this level if (!this.levels.isResourceAbsent(tile)) this.requestTexture(dc, tile); } } MercatorTextureTile[] subTiles = tile.createSubTiles(this.levels .getLevel(tile.getLevelNumber() + 1)); for (MercatorTextureTile child : subTiles) { if (this.isTileVisible(dc, child)) this.addTileOrDescendants(dc, child); } } finally { if (ancestorResource != null) // Pop this tile as the currentResource ancestor this.currentResourceTile = ancestorResource; } } private void addTile(DrawContext dc, MercatorTextureTile tile) { tile.setFallbackTile(null); if (tile.isTextureInMemory(dc.getTextureCache())) { // System.out.printf("Sector %s, min = %f, max = %f\n", tile.getSector(), // dc.getGlobe().getMinElevation(tile.getSector()), dc.getGlobe().getMaxElevation(tile.getSector())); this.addTileToCurrent(tile); return; } // Level 0 loads may be forced if (tile.getLevelNumber() == 0 && this.forceLevelZeroLoads && !tile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(tile); if (tile.isTextureInMemory(dc.getTextureCache())) { this.addTileToCurrent(tile); return; } } // Tile's texture isn't available, so request it if (tile.getLevelNumber() < this.levels.getNumLevels()) { // Request only tiles with data associated at this level if (!this.levels.isResourceAbsent(tile)) this.requestTexture(dc, tile); } // Set up to use the currentResource tile's texture if (this.currentResourceTile != null) { if (this.currentResourceTile.getLevelNumber() == 0 && this.forceLevelZeroLoads && !this.currentResourceTile.isTextureInMemory(dc .getTextureCache()) && !this.currentResourceTile.isTextureInMemory(dc .getTextureCache())) this.forceTextureLoad(this.currentResourceTile); if (this.currentResourceTile .isTextureInMemory(dc.getTextureCache())) { tile.setFallbackTile(currentResourceTile); this.addTileToCurrent(tile); } } } private void addTileToCurrent(MercatorTextureTile tile) { this.currentTiles.add(tile); } private boolean isTileVisible(DrawContext dc, MercatorTextureTile tile) { // if (!(tile.getExtent(dc).intersects(dc.getView().getFrustumInModelCoordinates()) // && (dc.getVisibleSector() == null || dc.getVisibleSector().intersects(tile.getSector())))) // return false; // // Position eyePos = dc.getView().getEyePosition(); // LatLon centroid = tile.getSector().getCentroid(); // Angle d = LatLon.greatCircleDistance(eyePos.getLatLon(), centroid); // if ((!tile.getLevelName().equals("0")) && d.compareTo(tile.getSector().getDeltaLat().multiply(2.5)) == 1) // return false; // // return true; // return tile.getExtent(dc).intersects( dc.getView().getFrustumInModelCoordinates()) && (dc.getVisibleSector() == null || dc.getVisibleSector() .intersects(tile.getSector())); } // // private boolean meetsRenderCriteria2(DrawContext dc, TextureTile tile) // { // if (this.levels.isFinalLevel(tile.getLevelNumber())) // return true; // // Sector sector = tile.getSector(); // Vec4[] corners = sector.computeCornerPoints(dc.getGlobe()); // Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe()); // // View view = dc.getView(); // double d1 = view.getEyePoint().distanceTo3(corners[0]); // double d2 = view.getEyePoint().distanceTo3(corners[1]); // double d3 = view.getEyePoint().distanceTo3(corners[2]); // double d4 = view.getEyePoint().distanceTo3(corners[3]); // double d5 = view.getEyePoint().distanceTo3(centerPoint); // // double minDistance = d1; // if (d2 < minDistance) // minDistance = d2; // if (d3 < minDistance) // minDistance = d3; // if (d4 < minDistance) // minDistance = d4; // if (d5 < minDistance) // minDistance = d5; // // double r = 0; // if (minDistance == d1) // r = corners[0].getLength3(); // if (minDistance == d2) // r = corners[1].getLength3(); // if (minDistance == d3) // r = corners[2].getLength3(); // if (minDistance == d4) // r = corners[3].getLength3(); // if (minDistance == d5) // r = centerPoint.getLength3(); // // double texelSize = tile.getLevel().getTexelSize(r); // double pixelSize = dc.getView().computePixelSizeAtDistance(minDistance); // // return 2 * pixelSize >= texelSize; // } private boolean meetsRenderCriteria(DrawContext dc, MercatorTextureTile tile) { return this.levels.isFinalLevel(tile.getLevelNumber()) || !needToSplit(dc, tile.getSector()); } private boolean needToSplit(DrawContext dc, Sector sector) { Vec4[] corners = sector.computeCornerPoints(dc.getGlobe(), dc.getVerticalExaggeration()); Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration()); View view = dc.getView(); double d1 = view.getEyePoint().distanceTo3(corners[0]); double d2 = view.getEyePoint().distanceTo3(corners[1]); double d3 = view.getEyePoint().distanceTo3(corners[2]); double d4 = view.getEyePoint().distanceTo3(corners[3]); double d5 = view.getEyePoint().distanceTo3(centerPoint); double minDistance = d1; if (d2 < minDistance) minDistance = d2; if (d3 < minDistance) minDistance = d3; if (d4 < minDistance) minDistance = d4; if (d5 < minDistance) minDistance = d5; double cellSize = (Math.PI * sector.getDeltaLatRadians() * dc .getGlobe().getRadius()) / 20; // TODO return !(Math.log10(cellSize) <= (Math.log10(minDistance) - this.splitScale)); } private boolean atMaxLevel(DrawContext dc) { Position vpc = dc.getViewportCenterPosition(); if (dc.getView() == null || this.getLevels() == null || vpc == null) return false; if (!this.getLevels().getSector().contains(vpc.getLatitude(), vpc.getLongitude())) return true; Level nextToLast = this.getLevels().getNextToLastLevel(); if (nextToLast == null) return true; Sector centerSector = nextToLast.computeSectorForPosition(vpc.getLatitude(), vpc.getLongitude(), this.getLevels().getTileOrigin()); return this.needToSplit(dc, centerSector); } // ============== Rendering ======================= // // ============== Rendering ======================= // // ============== Rendering ======================= // @Override public void render(DrawContext dc) { this.atMaxResolution = this.atMaxLevel(dc); super.render(dc); } @Override protected final void doRender(DrawContext dc) { if (this.forceLevelZeroLoads && !this.levelZeroLoaded) this.loadAllTopLevelTextures(dc); if (dc.getSurfaceGeometry() == null || dc.getSurfaceGeometry().size() < 1) return; dc.getGeographicSurfaceTileRenderer().setShowImageTileOutlines( this.showImageTileOutlines); draw(dc); } private void draw(DrawContext dc) { this.referencePoint = this.computeReferencePoint(dc); this.assembleTiles(dc); // Determine the tiles to draw. if (this.currentTiles.size() >= 1) { MercatorTextureTile[] sortedTiles = new MercatorTextureTile[this.currentTiles .size()]; sortedTiles = this.currentTiles.toArray(sortedTiles); Arrays.sort(sortedTiles, levelComparer); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. if (this.isUseTransparentTextures() || this.getOpacity() < 1) { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT | GL2.GL_CURRENT_BIT); gl.glColor4d(1d, 1d, 1d, this.getOpacity()); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } else { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT); } gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); dc.setPerFrameStatistic(PerformanceStatistic.IMAGE_TILE_COUNT, this.tileCountName, this.currentTiles.size()); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.currentTiles); gl.glPopAttrib(); if (this.drawTileIDs) this.drawTileIDs(dc, this.currentTiles); if (this.drawBoundingVolumes) this.drawBoundingVolumes(dc, this.currentTiles); this.currentTiles.clear(); } this.sendRequests(); this.requestQ.clear(); } private void sendRequests() { Runnable task = this.requestQ.poll(); while (task != null) { if (!WorldWind.getTaskService().isFull()) { WorldWind.getTaskService().addTask(task); } task = this.requestQ.poll(); } } public boolean isLayerInView(DrawContext dc) { if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (dc.getView() == null) { String message = Logging .getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } return !(dc.getVisibleSector() != null && !this.levels.getSector() .intersects(dc.getVisibleSector())); } private Vec4 computeReferencePoint(DrawContext dc) { if (dc.getViewportCenterPosition() != null) return dc.getGlobe().computePointFromPosition( dc.getViewportCenterPosition()); java.awt.geom.Rectangle2D viewport = dc.getView().getViewport(); int x = (int) viewport.getWidth() / 2; for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) { Position pos = dc.getView().computePositionFromScreenPoint(x, y); if (pos == null) continue; return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), 0d); } return null; } protected Vec4 getReferencePoint() { return this.referencePoint; } private static class LevelComparer implements Comparator<MercatorTextureTile> { public int compare(MercatorTextureTile ta, MercatorTextureTile tb) { int la = ta.getFallbackTile() == null ? ta.getLevelNumber() : ta .getFallbackTile().getLevelNumber(); int lb = tb.getFallbackTile() == null ? tb.getLevelNumber() : tb .getFallbackTile().getLevelNumber(); return la < lb ? -1 : la == lb ? 0 : 1; } } private void drawTileIDs(DrawContext dc, ArrayList<MercatorTextureTile> tiles) { java.awt.Rectangle viewport = dc.getView().getViewport(); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), java.awt.Font.decode("Arial-Plain-13")); dc.getGL().glDisable(GL.GL_DEPTH_TEST); dc.getGL().glDisable(GL.GL_BLEND); dc.getGL().glDisable(GL.GL_TEXTURE_2D); textRenderer.setColor(java.awt.Color.YELLOW); textRenderer.beginRendering(viewport.width, viewport.height); for (MercatorTextureTile tile : tiles) { String tileLabel = tile.getLabel(); if (tile.getFallbackTile() != null) tileLabel += "/" + tile.getFallbackTile().getLabel(); LatLon ll = tile.getSector().getCentroid(); Vec4 pt = dc.getGlobe().computePointFromPosition( ll.getLatitude(), ll.getLongitude(), dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); pt = dc.getView().project(pt); textRenderer.draw(tileLabel, (int) pt.x, (int) pt.y); } textRenderer.endRendering(); } private void drawBoundingVolumes(DrawContext dc, ArrayList<MercatorTextureTile> tiles) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. float[] previousColor = new float[4]; gl.glGetFloatv(GL2.GL_CURRENT_COLOR, previousColor, 0); gl.glColor3d(0, 1, 0); for (MercatorTextureTile tile : tiles) { ((Cylinder) tile.getExtent(dc)).render(dc); } Cylinder c = Sector.computeBoundingCylinder(dc.getGlobe(), dc.getVerticalExaggeration(), this.levels.getSector()); gl.glColor3d(1, 1, 0); c.render(dc); gl.glColor4fv(previousColor, 0); } // ============== Image Composition ======================= // // ============== Image Composition ======================= // // ============== Image Composition ======================= // public List<String> getAvailableImageFormats() { return new ArrayList<String>(this.supportedImageFormats); } public boolean isImageFormatAvailable(String imageFormat) { return imageFormat != null && this.supportedImageFormats.contains(imageFormat); } public String getDefaultImageFormat() { return this.supportedImageFormats.size() > 0 ? this.supportedImageFormats .get(0) : null; } protected void setAvailableImageFormats(String[] formats) { this.supportedImageFormats.clear(); if (formats != null) { this.supportedImageFormats.addAll(Arrays.asList(formats)); } } private BufferedImage requestImage(MercatorTextureTile tile, String mimeType) throws URISyntaxException { String pathBase = tile.getPath().substring(0, tile.getPath().lastIndexOf(".")); String suffix = WWIO.makeSuffixForMimeType(mimeType); String path = pathBase + suffix; URL url = this.getDataFileStore().findFile(path, false); if (url == null) // image is not local return null; if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) { // The file has expired. Delete it. this.getDataFileStore().removeFile(url); String message = Logging.getMessage("generic.DataFileExpired", url); Logging.logger().fine(message); } else { try { File imageFile = new File(url.toURI()); BufferedImage image = ImageIO.read(imageFile); if (image == null) { String message = Logging.getMessage( "generic.ImageReadFailed", imageFile); throw new RuntimeException(message); } this.levels.unmarkResourceAbsent(tile); return image; } catch (IOException e) { // Assume that something's wrong with the file and delete it. this.getDataFileStore().removeFile(url); this.levels.markResourceAbsent(tile); String message = Logging.getMessage( "generic.DeletedCorruptDataFile", url); Logging.logger().info(message); } } return null; } private void downloadImage(final MercatorTextureTile tile, String mimeType) throws Exception { // System.out.println(tile.getPath()); final URL resourceURL = tile.getResourceURL(mimeType); Retriever retriever; String protocol = resourceURL.getProtocol(); if ("http".equalsIgnoreCase(protocol)) { retriever = new HTTPRetriever(resourceURL, new HttpRetrievalPostProcessor(tile)); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers } else { String message = Logging .getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL); throw new RuntimeException(message); } retriever.setConnectTimeout(10000); retriever.setReadTimeout(20000); retriever.call(); } public int computeLevelForResolution(Sector sector, Globe globe, double resolution) { if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } double texelSize = 0; Level targetLevel = this.levels.getLastLevel(); for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { if (this.levels.isLevelEmpty(i)) continue; texelSize = this.levels.getLevel(i).getTexelSize(); if (texelSize > resolution) continue; targetLevel = this.levels.getLevel(i); break; } Logging.logger().info( Logging.getMessage("layers.TiledImageLayer.LevelSelection", targetLevel.getLevelNumber(), texelSize)); return targetLevel.getLevelNumber(); } public BufferedImage composeImageForSector(Sector sector, int imageWidth, int imageHeight, int levelNumber, String mimeType, boolean abortOnError, BufferedImage image) { if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (levelNumber < 0) { levelNumber = this.levels.getLastLevel().getLevelNumber(); } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) { Logging.logger().warning( Logging.getMessage( "generic.LevelRequestedGreaterThanMaxLevel", levelNumber, this.levels.getLastLevel() .getLevelNumber())); levelNumber = this.levels.getLastLevel().getLevelNumber(); } MercatorTextureTile[][] tiles = this.getTilesInSector(sector, levelNumber); if (tiles.length == 0 || tiles[0].length == 0) { Logging .logger() .severe( Logging .getMessage("layers.TiledImageLayer.NoImagesAvailable")); return null; } if (image == null) image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); for (MercatorTextureTile[] row : tiles) { for (MercatorTextureTile tile : row) { if (tile == null) continue; BufferedImage tileImage; try { tileImage = this.getImage(tile, mimeType); double sh = ((double) imageHeight / (double) tileImage .getHeight()) * (tile.getSector().getDeltaLat().divide(sector .getDeltaLat())); double sw = ((double) imageWidth / (double) tileImage .getWidth()) * (tile.getSector().getDeltaLon().divide(sector .getDeltaLon())); double dh = imageHeight * (-tile.getSector().getMaxLatitude().subtract( sector.getMaxLatitude()).degrees / sector .getDeltaLat().degrees); double dw = imageWidth * (tile.getSector().getMinLongitude().subtract( sector.getMinLongitude()).degrees / sector .getDeltaLon().degrees); AffineTransform txf = g.getTransform(); g.translate(dw, dh); g.scale(sw, sh); g.drawImage(tileImage, 0, 0, null); g.setTransform(txf); } catch (Exception e) { if (abortOnError) throw new RuntimeException(e); String message = Logging.getMessage( "generic.ExceptionWhileRequestingImage", tile .getPath()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); } } } return image; } public int countImagesInSector(Sector sector, int levelNumber) { if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); if (levelNumber >= 0) { for (int i = levelNumber; i < this.getLevels().getLastLevel() .getLevelNumber(); i++) { if (this.levels.isLevelEmpty(i)) continue; targetLevel = this.levels.getLevel(i); break; } } // Collect all the tiles intersecting the input sector. LatLon delta = targetLevel.getTileDelta(); Angle latOrigin = this.levels.getTileOrigin().getLatitude(); Angle lonOrigin = this.levels.getTileOrigin().getLongitude(); final int nwRow = Tile.computeRow(delta.getLatitude(), sector .getMaxLatitude(), latOrigin); final int nwCol = Tile.computeColumn(delta.getLongitude(), sector .getMinLongitude(), lonOrigin); final int seRow = Tile.computeRow(delta.getLatitude(), sector .getMinLatitude(), latOrigin); final int seCol = Tile.computeColumn(delta.getLongitude(), sector .getMaxLongitude(), lonOrigin); int numRows = nwRow - seRow + 1; int numCols = seCol - nwCol + 1; return numRows * numCols; } private MercatorTextureTile[][] getTilesInSector(Sector sector, int levelNumber) { if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); if (levelNumber >= 0) { for (int i = levelNumber; i < this.getLevels().getLastLevel() .getLevelNumber(); i++) { if (this.levels.isLevelEmpty(i)) continue; targetLevel = this.levels.getLevel(i); break; } } // Collect all the tiles intersecting the input sector. LatLon delta = targetLevel.getTileDelta(); Angle latOrigin = this.levels.getTileOrigin().getLatitude(); Angle lonOrigin = this.levels.getTileOrigin().getLongitude(); final int nwRow = Tile.computeRow(delta.getLatitude(), sector .getMaxLatitude(), latOrigin); final int nwCol = Tile.computeColumn(delta.getLongitude(), sector .getMinLongitude(), lonOrigin); final int seRow = Tile.computeRow(delta.getLatitude(), sector .getMinLatitude(), latOrigin); final int seCol = Tile.computeColumn(delta.getLongitude(), sector .getMaxLongitude(), lonOrigin); int numRows = nwRow - seRow + 1; int numCols = seCol - nwCol + 1; MercatorTextureTile[][] sectorTiles = new MercatorTextureTile[numRows][numCols]; for (int row = nwRow; row >= seRow; row--) { for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName()); Sector tileSector = this.levels.computeSectorForKey(key); MercatorSector mSector = MercatorSector.fromSector(tileSector); //TODO: check sectorTiles[nwRow - row][col - nwCol] = new MercatorTextureTile( mSector, targetLevel, row, col); } } return sectorTiles; } private BufferedImage getImage(MercatorTextureTile tile, String mimeType) throws Exception { // Read the image from disk. BufferedImage image = this.requestImage(tile, mimeType); if (image != null) return image; // Retrieve it from the net since it's not on disk. this.downloadImage(tile, mimeType); // Try to read from disk again after retrieving it from the net. image = this.requestImage(tile, mimeType); if (image == null) { String message = Logging.getMessage( "layers.TiledImageLayer.ImageUnavailable", tile.getPath()); throw new RuntimeException(message); } return image; } private class HttpRetrievalPostProcessor implements RetrievalPostProcessor { private MercatorTextureTile tile; public HttpRetrievalPostProcessor(MercatorTextureTile tile) { this.tile = tile; } public ByteBuffer run(Retriever retriever) { if (!retriever.getState().equals( Retriever.RETRIEVER_STATE_SUCCESSFUL)) return null; HTTPRetriever htr = (HTTPRetriever) retriever; if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // Mark tile as missing to avoid excessive attempts MercatorTiledImageLayer.this.levels.markResourceAbsent(tile); return null; } if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) return null; URLRetriever r = (URLRetriever) retriever; ByteBuffer buffer = r.getBuffer(); String suffix = WWIO.makeSuffixForMimeType(htr.getContentType()); if (suffix == null) { return null; // TODO: log error } String path = tile.getPath().substring(0, tile.getPath().lastIndexOf(".")); path += suffix; final File outFile = getDataFileStore().newFile(path); if (outFile == null) return null; try { WWIO.saveBuffer(buffer, outFile); return buffer; } catch (IOException e) { e.printStackTrace(); // TODO: log error return null; } } } }
apache-2.0
phoenixsbk/kvmmgr
backend/manager/modules/restapi/interface/definition/xjc/org/ovirt/engine/api/model/ErrorHandlingOptions.java
2555
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-b10 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.06.13 at 03:17:43 PM CST // package org.ovirt.engine.api.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ErrorHandlingOptions complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ErrorHandlingOptions"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="on_error" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ErrorHandlingOptions", propOrder = { "errorHandling" }) public class ErrorHandlingOptions { @XmlElement(name = "on_error") protected List<String> errorHandling; /** * Gets the value of the errorHandling property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the errorHandling property. * * <p> * For example, to add a new item, do as follows: * <pre> * getErrorHandling().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getErrorHandling() { if (errorHandling == null) { errorHandling = new ArrayList<String>(); } return this.errorHandling; } public boolean isSetErrorHandling() { return ((this.errorHandling!= null)&&(!this.errorHandling.isEmpty())); } public void unsetErrorHandling() { this.errorHandling = null; } }
apache-2.0
rharnls72/Calculate_Rate
Calculate_Rate/src/main/User.java
433
package src/main; public class User { private String type; private int numberofline; private double minutesofuse; public User(String type, int numberofline, double minutesofuse) { this.type=type; this.numberofline = numberofline; this.minutesofuse = minutesofuse; } public String getType() {return type;} public int getNumberofline() {return numberofline;} public double getMinutesofuse() {return minutesofuse;} }
apache-2.0
googleapis/java-security-private-ca
google-cloud-security-private-ca/src/main/java/com/google/cloud/security/privateca/v1/CertificateAuthorityServiceSettings.java
39682
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.security.privateca.v1; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListCaPoolsPagedResponse; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListCertificateAuthoritiesPagedResponse; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListCertificateRevocationListsPagedResponse; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListCertificateTemplatesPagedResponse; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListCertificatesPagedResponse; import static com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient.ListLocationsPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.cloud.security.privateca.v1.stub.CertificateAuthorityServiceStubSettings; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link CertificateAuthorityServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (privateca.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of createCertificate to 30 seconds: * * <pre>{@code * CertificateAuthorityServiceSettings.Builder certificateAuthorityServiceSettingsBuilder = * CertificateAuthorityServiceSettings.newBuilder(); * certificateAuthorityServiceSettingsBuilder * .createCertificateSettings() * .setRetrySettings( * certificateAuthorityServiceSettingsBuilder * .createCertificateSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * CertificateAuthorityServiceSettings certificateAuthorityServiceSettings = * certificateAuthorityServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class CertificateAuthorityServiceSettings extends ClientSettings<CertificateAuthorityServiceSettings> { /** Returns the object with the settings used for calls to createCertificate. */ public UnaryCallSettings<CreateCertificateRequest, Certificate> createCertificateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCertificateSettings(); } /** Returns the object with the settings used for calls to getCertificate. */ public UnaryCallSettings<GetCertificateRequest, Certificate> getCertificateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).getCertificateSettings(); } /** Returns the object with the settings used for calls to listCertificates. */ public PagedCallSettings< ListCertificatesRequest, ListCertificatesResponse, ListCertificatesPagedResponse> listCertificatesSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).listCertificatesSettings(); } /** Returns the object with the settings used for calls to revokeCertificate. */ public UnaryCallSettings<RevokeCertificateRequest, Certificate> revokeCertificateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .revokeCertificateSettings(); } /** Returns the object with the settings used for calls to updateCertificate. */ public UnaryCallSettings<UpdateCertificateRequest, Certificate> updateCertificateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateSettings(); } /** Returns the object with the settings used for calls to activateCertificateAuthority. */ public UnaryCallSettings<ActivateCertificateAuthorityRequest, Operation> activateCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .activateCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to activateCertificateAuthority. */ public OperationCallSettings< ActivateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> activateCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .activateCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to createCertificateAuthority. */ public UnaryCallSettings<CreateCertificateAuthorityRequest, Operation> createCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to createCertificateAuthority. */ public OperationCallSettings< CreateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> createCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to disableCertificateAuthority. */ public UnaryCallSettings<DisableCertificateAuthorityRequest, Operation> disableCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .disableCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to disableCertificateAuthority. */ public OperationCallSettings< DisableCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> disableCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .disableCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to enableCertificateAuthority. */ public UnaryCallSettings<EnableCertificateAuthorityRequest, Operation> enableCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .enableCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to enableCertificateAuthority. */ public OperationCallSettings< EnableCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> enableCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .enableCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to fetchCertificateAuthorityCsr. */ public UnaryCallSettings< FetchCertificateAuthorityCsrRequest, FetchCertificateAuthorityCsrResponse> fetchCertificateAuthorityCsrSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .fetchCertificateAuthorityCsrSettings(); } /** Returns the object with the settings used for calls to getCertificateAuthority. */ public UnaryCallSettings<GetCertificateAuthorityRequest, CertificateAuthority> getCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .getCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to listCertificateAuthorities. */ public PagedCallSettings< ListCertificateAuthoritiesRequest, ListCertificateAuthoritiesResponse, ListCertificateAuthoritiesPagedResponse> listCertificateAuthoritiesSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .listCertificateAuthoritiesSettings(); } /** Returns the object with the settings used for calls to undeleteCertificateAuthority. */ public UnaryCallSettings<UndeleteCertificateAuthorityRequest, Operation> undeleteCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .undeleteCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to undeleteCertificateAuthority. */ public OperationCallSettings< UndeleteCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> undeleteCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .undeleteCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to deleteCertificateAuthority. */ public UnaryCallSettings<DeleteCertificateAuthorityRequest, Operation> deleteCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .deleteCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to deleteCertificateAuthority. */ public OperationCallSettings< DeleteCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> deleteCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .deleteCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to updateCertificateAuthority. */ public UnaryCallSettings<UpdateCertificateAuthorityRequest, Operation> updateCertificateAuthoritySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateAuthoritySettings(); } /** Returns the object with the settings used for calls to updateCertificateAuthority. */ public OperationCallSettings< UpdateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> updateCertificateAuthorityOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateAuthorityOperationSettings(); } /** Returns the object with the settings used for calls to createCaPool. */ public UnaryCallSettings<CreateCaPoolRequest, Operation> createCaPoolSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).createCaPoolSettings(); } /** Returns the object with the settings used for calls to createCaPool. */ public OperationCallSettings<CreateCaPoolRequest, CaPool, OperationMetadata> createCaPoolOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCaPoolOperationSettings(); } /** Returns the object with the settings used for calls to updateCaPool. */ public UnaryCallSettings<UpdateCaPoolRequest, Operation> updateCaPoolSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).updateCaPoolSettings(); } /** Returns the object with the settings used for calls to updateCaPool. */ public OperationCallSettings<UpdateCaPoolRequest, CaPool, OperationMetadata> updateCaPoolOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCaPoolOperationSettings(); } /** Returns the object with the settings used for calls to getCaPool. */ public UnaryCallSettings<GetCaPoolRequest, CaPool> getCaPoolSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).getCaPoolSettings(); } /** Returns the object with the settings used for calls to listCaPools. */ public PagedCallSettings<ListCaPoolsRequest, ListCaPoolsResponse, ListCaPoolsPagedResponse> listCaPoolsSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).listCaPoolsSettings(); } /** Returns the object with the settings used for calls to deleteCaPool. */ public UnaryCallSettings<DeleteCaPoolRequest, Operation> deleteCaPoolSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).deleteCaPoolSettings(); } /** Returns the object with the settings used for calls to deleteCaPool. */ public OperationCallSettings<DeleteCaPoolRequest, Empty, OperationMetadata> deleteCaPoolOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .deleteCaPoolOperationSettings(); } /** Returns the object with the settings used for calls to fetchCaCerts. */ public UnaryCallSettings<FetchCaCertsRequest, FetchCaCertsResponse> fetchCaCertsSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).fetchCaCertsSettings(); } /** Returns the object with the settings used for calls to getCertificateRevocationList. */ public UnaryCallSettings<GetCertificateRevocationListRequest, CertificateRevocationList> getCertificateRevocationListSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .getCertificateRevocationListSettings(); } /** Returns the object with the settings used for calls to listCertificateRevocationLists. */ public PagedCallSettings< ListCertificateRevocationListsRequest, ListCertificateRevocationListsResponse, ListCertificateRevocationListsPagedResponse> listCertificateRevocationListsSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .listCertificateRevocationListsSettings(); } /** Returns the object with the settings used for calls to updateCertificateRevocationList. */ public UnaryCallSettings<UpdateCertificateRevocationListRequest, Operation> updateCertificateRevocationListSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateRevocationListSettings(); } /** Returns the object with the settings used for calls to updateCertificateRevocationList. */ public OperationCallSettings< UpdateCertificateRevocationListRequest, CertificateRevocationList, OperationMetadata> updateCertificateRevocationListOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateRevocationListOperationSettings(); } /** Returns the object with the settings used for calls to createCertificateTemplate. */ public UnaryCallSettings<CreateCertificateTemplateRequest, Operation> createCertificateTemplateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCertificateTemplateSettings(); } /** Returns the object with the settings used for calls to createCertificateTemplate. */ public OperationCallSettings< CreateCertificateTemplateRequest, CertificateTemplate, OperationMetadata> createCertificateTemplateOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .createCertificateTemplateOperationSettings(); } /** Returns the object with the settings used for calls to deleteCertificateTemplate. */ public UnaryCallSettings<DeleteCertificateTemplateRequest, Operation> deleteCertificateTemplateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .deleteCertificateTemplateSettings(); } /** Returns the object with the settings used for calls to deleteCertificateTemplate. */ public OperationCallSettings<DeleteCertificateTemplateRequest, Empty, OperationMetadata> deleteCertificateTemplateOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .deleteCertificateTemplateOperationSettings(); } /** Returns the object with the settings used for calls to getCertificateTemplate. */ public UnaryCallSettings<GetCertificateTemplateRequest, CertificateTemplate> getCertificateTemplateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .getCertificateTemplateSettings(); } /** Returns the object with the settings used for calls to listCertificateTemplates. */ public PagedCallSettings< ListCertificateTemplatesRequest, ListCertificateTemplatesResponse, ListCertificateTemplatesPagedResponse> listCertificateTemplatesSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .listCertificateTemplatesSettings(); } /** Returns the object with the settings used for calls to updateCertificateTemplate. */ public UnaryCallSettings<UpdateCertificateTemplateRequest, Operation> updateCertificateTemplateSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateTemplateSettings(); } /** Returns the object with the settings used for calls to updateCertificateTemplate. */ public OperationCallSettings< UpdateCertificateTemplateRequest, CertificateTemplate, OperationMetadata> updateCertificateTemplateOperationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .updateCertificateTemplateOperationSettings(); } /** Returns the object with the settings used for calls to listLocations. */ public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).listLocationsSettings(); } /** Returns the object with the settings used for calls to getLocation. */ public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).getLocationSettings(); } /** Returns the object with the settings used for calls to setIamPolicy. */ public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).setIamPolicySettings(); } /** Returns the object with the settings used for calls to getIamPolicy. */ public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()).getIamPolicySettings(); } /** Returns the object with the settings used for calls to testIamPermissions. */ public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings() { return ((CertificateAuthorityServiceStubSettings) getStubSettings()) .testIamPermissionsSettings(); } public static final CertificateAuthorityServiceSettings create( CertificateAuthorityServiceStubSettings stub) throws IOException { return new CertificateAuthorityServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return CertificateAuthorityServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return CertificateAuthorityServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return CertificateAuthorityServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return CertificateAuthorityServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return CertificateAuthorityServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return CertificateAuthorityServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return CertificateAuthorityServiceStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected CertificateAuthorityServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for CertificateAuthorityServiceSettings. */ public static class Builder extends ClientSettings.Builder<CertificateAuthorityServiceSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(CertificateAuthorityServiceStubSettings.newBuilder(clientContext)); } protected Builder(CertificateAuthorityServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(CertificateAuthorityServiceStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(CertificateAuthorityServiceStubSettings.newBuilder()); } public CertificateAuthorityServiceStubSettings.Builder getStubSettingsBuilder() { return ((CertificateAuthorityServiceStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to createCertificate. */ public UnaryCallSettings.Builder<CreateCertificateRequest, Certificate> createCertificateSettings() { return getStubSettingsBuilder().createCertificateSettings(); } /** Returns the builder for the settings used for calls to getCertificate. */ public UnaryCallSettings.Builder<GetCertificateRequest, Certificate> getCertificateSettings() { return getStubSettingsBuilder().getCertificateSettings(); } /** Returns the builder for the settings used for calls to listCertificates. */ public PagedCallSettings.Builder< ListCertificatesRequest, ListCertificatesResponse, ListCertificatesPagedResponse> listCertificatesSettings() { return getStubSettingsBuilder().listCertificatesSettings(); } /** Returns the builder for the settings used for calls to revokeCertificate. */ public UnaryCallSettings.Builder<RevokeCertificateRequest, Certificate> revokeCertificateSettings() { return getStubSettingsBuilder().revokeCertificateSettings(); } /** Returns the builder for the settings used for calls to updateCertificate. */ public UnaryCallSettings.Builder<UpdateCertificateRequest, Certificate> updateCertificateSettings() { return getStubSettingsBuilder().updateCertificateSettings(); } /** Returns the builder for the settings used for calls to activateCertificateAuthority. */ public UnaryCallSettings.Builder<ActivateCertificateAuthorityRequest, Operation> activateCertificateAuthoritySettings() { return getStubSettingsBuilder().activateCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to activateCertificateAuthority. */ public OperationCallSettings.Builder< ActivateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> activateCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().activateCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to createCertificateAuthority. */ public UnaryCallSettings.Builder<CreateCertificateAuthorityRequest, Operation> createCertificateAuthoritySettings() { return getStubSettingsBuilder().createCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to createCertificateAuthority. */ public OperationCallSettings.Builder< CreateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> createCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().createCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to disableCertificateAuthority. */ public UnaryCallSettings.Builder<DisableCertificateAuthorityRequest, Operation> disableCertificateAuthoritySettings() { return getStubSettingsBuilder().disableCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to disableCertificateAuthority. */ public OperationCallSettings.Builder< DisableCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> disableCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().disableCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to enableCertificateAuthority. */ public UnaryCallSettings.Builder<EnableCertificateAuthorityRequest, Operation> enableCertificateAuthoritySettings() { return getStubSettingsBuilder().enableCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to enableCertificateAuthority. */ public OperationCallSettings.Builder< EnableCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> enableCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().enableCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to fetchCertificateAuthorityCsr. */ public UnaryCallSettings.Builder< FetchCertificateAuthorityCsrRequest, FetchCertificateAuthorityCsrResponse> fetchCertificateAuthorityCsrSettings() { return getStubSettingsBuilder().fetchCertificateAuthorityCsrSettings(); } /** Returns the builder for the settings used for calls to getCertificateAuthority. */ public UnaryCallSettings.Builder<GetCertificateAuthorityRequest, CertificateAuthority> getCertificateAuthoritySettings() { return getStubSettingsBuilder().getCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to listCertificateAuthorities. */ public PagedCallSettings.Builder< ListCertificateAuthoritiesRequest, ListCertificateAuthoritiesResponse, ListCertificateAuthoritiesPagedResponse> listCertificateAuthoritiesSettings() { return getStubSettingsBuilder().listCertificateAuthoritiesSettings(); } /** Returns the builder for the settings used for calls to undeleteCertificateAuthority. */ public UnaryCallSettings.Builder<UndeleteCertificateAuthorityRequest, Operation> undeleteCertificateAuthoritySettings() { return getStubSettingsBuilder().undeleteCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to undeleteCertificateAuthority. */ public OperationCallSettings.Builder< UndeleteCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> undeleteCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().undeleteCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to deleteCertificateAuthority. */ public UnaryCallSettings.Builder<DeleteCertificateAuthorityRequest, Operation> deleteCertificateAuthoritySettings() { return getStubSettingsBuilder().deleteCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to deleteCertificateAuthority. */ public OperationCallSettings.Builder< DeleteCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> deleteCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().deleteCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to updateCertificateAuthority. */ public UnaryCallSettings.Builder<UpdateCertificateAuthorityRequest, Operation> updateCertificateAuthoritySettings() { return getStubSettingsBuilder().updateCertificateAuthoritySettings(); } /** Returns the builder for the settings used for calls to updateCertificateAuthority. */ public OperationCallSettings.Builder< UpdateCertificateAuthorityRequest, CertificateAuthority, OperationMetadata> updateCertificateAuthorityOperationSettings() { return getStubSettingsBuilder().updateCertificateAuthorityOperationSettings(); } /** Returns the builder for the settings used for calls to createCaPool. */ public UnaryCallSettings.Builder<CreateCaPoolRequest, Operation> createCaPoolSettings() { return getStubSettingsBuilder().createCaPoolSettings(); } /** Returns the builder for the settings used for calls to createCaPool. */ public OperationCallSettings.Builder<CreateCaPoolRequest, CaPool, OperationMetadata> createCaPoolOperationSettings() { return getStubSettingsBuilder().createCaPoolOperationSettings(); } /** Returns the builder for the settings used for calls to updateCaPool. */ public UnaryCallSettings.Builder<UpdateCaPoolRequest, Operation> updateCaPoolSettings() { return getStubSettingsBuilder().updateCaPoolSettings(); } /** Returns the builder for the settings used for calls to updateCaPool. */ public OperationCallSettings.Builder<UpdateCaPoolRequest, CaPool, OperationMetadata> updateCaPoolOperationSettings() { return getStubSettingsBuilder().updateCaPoolOperationSettings(); } /** Returns the builder for the settings used for calls to getCaPool. */ public UnaryCallSettings.Builder<GetCaPoolRequest, CaPool> getCaPoolSettings() { return getStubSettingsBuilder().getCaPoolSettings(); } /** Returns the builder for the settings used for calls to listCaPools. */ public PagedCallSettings.Builder< ListCaPoolsRequest, ListCaPoolsResponse, ListCaPoolsPagedResponse> listCaPoolsSettings() { return getStubSettingsBuilder().listCaPoolsSettings(); } /** Returns the builder for the settings used for calls to deleteCaPool. */ public UnaryCallSettings.Builder<DeleteCaPoolRequest, Operation> deleteCaPoolSettings() { return getStubSettingsBuilder().deleteCaPoolSettings(); } /** Returns the builder for the settings used for calls to deleteCaPool. */ public OperationCallSettings.Builder<DeleteCaPoolRequest, Empty, OperationMetadata> deleteCaPoolOperationSettings() { return getStubSettingsBuilder().deleteCaPoolOperationSettings(); } /** Returns the builder for the settings used for calls to fetchCaCerts. */ public UnaryCallSettings.Builder<FetchCaCertsRequest, FetchCaCertsResponse> fetchCaCertsSettings() { return getStubSettingsBuilder().fetchCaCertsSettings(); } /** Returns the builder for the settings used for calls to getCertificateRevocationList. */ public UnaryCallSettings.Builder<GetCertificateRevocationListRequest, CertificateRevocationList> getCertificateRevocationListSettings() { return getStubSettingsBuilder().getCertificateRevocationListSettings(); } /** Returns the builder for the settings used for calls to listCertificateRevocationLists. */ public PagedCallSettings.Builder< ListCertificateRevocationListsRequest, ListCertificateRevocationListsResponse, ListCertificateRevocationListsPagedResponse> listCertificateRevocationListsSettings() { return getStubSettingsBuilder().listCertificateRevocationListsSettings(); } /** Returns the builder for the settings used for calls to updateCertificateRevocationList. */ public UnaryCallSettings.Builder<UpdateCertificateRevocationListRequest, Operation> updateCertificateRevocationListSettings() { return getStubSettingsBuilder().updateCertificateRevocationListSettings(); } /** Returns the builder for the settings used for calls to updateCertificateRevocationList. */ public OperationCallSettings.Builder< UpdateCertificateRevocationListRequest, CertificateRevocationList, OperationMetadata> updateCertificateRevocationListOperationSettings() { return getStubSettingsBuilder().updateCertificateRevocationListOperationSettings(); } /** Returns the builder for the settings used for calls to createCertificateTemplate. */ public UnaryCallSettings.Builder<CreateCertificateTemplateRequest, Operation> createCertificateTemplateSettings() { return getStubSettingsBuilder().createCertificateTemplateSettings(); } /** Returns the builder for the settings used for calls to createCertificateTemplate. */ public OperationCallSettings.Builder< CreateCertificateTemplateRequest, CertificateTemplate, OperationMetadata> createCertificateTemplateOperationSettings() { return getStubSettingsBuilder().createCertificateTemplateOperationSettings(); } /** Returns the builder for the settings used for calls to deleteCertificateTemplate. */ public UnaryCallSettings.Builder<DeleteCertificateTemplateRequest, Operation> deleteCertificateTemplateSettings() { return getStubSettingsBuilder().deleteCertificateTemplateSettings(); } /** Returns the builder for the settings used for calls to deleteCertificateTemplate. */ public OperationCallSettings.Builder<DeleteCertificateTemplateRequest, Empty, OperationMetadata> deleteCertificateTemplateOperationSettings() { return getStubSettingsBuilder().deleteCertificateTemplateOperationSettings(); } /** Returns the builder for the settings used for calls to getCertificateTemplate. */ public UnaryCallSettings.Builder<GetCertificateTemplateRequest, CertificateTemplate> getCertificateTemplateSettings() { return getStubSettingsBuilder().getCertificateTemplateSettings(); } /** Returns the builder for the settings used for calls to listCertificateTemplates. */ public PagedCallSettings.Builder< ListCertificateTemplatesRequest, ListCertificateTemplatesResponse, ListCertificateTemplatesPagedResponse> listCertificateTemplatesSettings() { return getStubSettingsBuilder().listCertificateTemplatesSettings(); } /** Returns the builder for the settings used for calls to updateCertificateTemplate. */ public UnaryCallSettings.Builder<UpdateCertificateTemplateRequest, Operation> updateCertificateTemplateSettings() { return getStubSettingsBuilder().updateCertificateTemplateSettings(); } /** Returns the builder for the settings used for calls to updateCertificateTemplate. */ public OperationCallSettings.Builder< UpdateCertificateTemplateRequest, CertificateTemplate, OperationMetadata> updateCertificateTemplateOperationSettings() { return getStubSettingsBuilder().updateCertificateTemplateOperationSettings(); } /** Returns the builder for the settings used for calls to listLocations. */ public PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return getStubSettingsBuilder().listLocationsSettings(); } /** Returns the builder for the settings used for calls to getLocation. */ public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() { return getStubSettingsBuilder().getLocationSettings(); } /** Returns the builder for the settings used for calls to setIamPolicy. */ public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() { return getStubSettingsBuilder().setIamPolicySettings(); } /** Returns the builder for the settings used for calls to getIamPolicy. */ public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() { return getStubSettingsBuilder().getIamPolicySettings(); } /** Returns the builder for the settings used for calls to testIamPermissions. */ public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings() { return getStubSettingsBuilder().testIamPermissionsSettings(); } @Override public CertificateAuthorityServiceSettings build() throws IOException { return new CertificateAuthorityServiceSettings(this); } } }
apache-2.0
VHAINNOVATIONS/AVS
ll-foundation/src/main/java/gov/va/med/lom/foundation/validate/ZipCodeValidator.java
1135
package gov.va.med.lom.foundation.validate; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ZipCodeValidator extends SinglePropertyValidator { private static final Pattern[] PATTERNS; static { PATTERNS = new Pattern[] {Pattern.compile("^[0-9][0-9][0-9][0-9][0-9]$"), Pattern.compile("^[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$"), Pattern.compile("^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$")}; } protected boolean isValid(Object value) { String ssn = (String) value; for (int i=0; i<PATTERNS.length; i++) { Matcher m = PATTERNS[i].matcher(ssn); if (m.matches()) { return true; } } return false; } public static boolean validate(Object value) { String ssn = (String) value; for (int i=0; i<PATTERNS.length; i++) { Matcher m = PATTERNS[i].matcher(ssn); if (m.matches()) { return true; } } return false; } protected String getMessageKey() { return "invalid.zip.code"; } public static String getErrorKey() { return "invalid.zip.code"; } }
apache-2.0
sjaco002/incubator-asterixdb-hyracks
hyracks/hyracks-dataflow-std/src/main/java/edu/uci/ics/hyracks/dataflow/std/group/hash/HashGroupBuildOperatorNodePushable.java
3789
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.hyracks.dataflow.std.group.hash; import java.nio.ByteBuffer; import edu.uci.ics.hyracks.api.context.IHyracksTaskContext; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory; import edu.uci.ics.hyracks.api.dataflow.value.ITuplePartitionComputerFactory; import edu.uci.ics.hyracks.api.dataflow.value.RecordDescriptor; import edu.uci.ics.hyracks.api.exceptions.HyracksDataException; import edu.uci.ics.hyracks.dataflow.common.comm.io.FrameTupleAccessor; import edu.uci.ics.hyracks.dataflow.std.base.AbstractUnaryInputSinkOperatorNodePushable; import edu.uci.ics.hyracks.dataflow.std.group.IAggregatorDescriptorFactory; class HashGroupBuildOperatorNodePushable extends AbstractUnaryInputSinkOperatorNodePushable { private final IHyracksTaskContext ctx; private final FrameTupleAccessor accessor; private final Object stateId; private final int[] keys; private final ITuplePartitionComputerFactory tpcf; private final IBinaryComparatorFactory[] comparatorFactories; private final IAggregatorDescriptorFactory aggregatorFactory; private final int tableSize; private final RecordDescriptor inRecordDescriptor; private final RecordDescriptor outRecordDescriptor; private HashGroupState state; HashGroupBuildOperatorNodePushable(IHyracksTaskContext ctx, Object stateId, int[] keys, ITuplePartitionComputerFactory tpcf, IBinaryComparatorFactory[] comparatorFactories, IAggregatorDescriptorFactory aggregatorFactory, int tableSize, RecordDescriptor inRecordDescriptor, RecordDescriptor outRecordDescriptor) { this.ctx = ctx; this.accessor = new FrameTupleAccessor(inRecordDescriptor); this.stateId = stateId; this.keys = keys; this.tpcf = tpcf; this.comparatorFactories = comparatorFactories; this.aggregatorFactory = aggregatorFactory; this.tableSize = tableSize; this.inRecordDescriptor = inRecordDescriptor; this.outRecordDescriptor = outRecordDescriptor; } @Override public void open() throws HyracksDataException { state = new HashGroupState(ctx.getJobletContext().getJobId(), stateId); state.setHashTable(new GroupingHashTable(ctx, keys, comparatorFactories, tpcf, aggregatorFactory, inRecordDescriptor, outRecordDescriptor, tableSize)); } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { GroupingHashTable table = state.getHashTable(); accessor.reset(buffer); int tupleCount = accessor.getTupleCount(); for (int i = 0; i < tupleCount; ++i) { try { table.insert(accessor, i); } catch (Exception e) { System.out.println(e.toString()); throw new HyracksDataException(e); } } } @Override public void close() throws HyracksDataException { ctx.setStateObject(state); } @Override public void fail() throws HyracksDataException { throw new HyracksDataException("HashGroupOperator is failed."); } }
apache-2.0
b2ihealthcare/snow-owl
fhir/com.b2international.snowowl.fhir.rest.tests/src/com/b2international/snowowl/fhir/tests/domain/structuredefinition/MappingTest.java
2384
/* * Copyright 2021 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.fhir.tests.domain.structuredefinition; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.b2international.snowowl.fhir.core.model.structuredefinition.Mapping; import com.b2international.snowowl.fhir.core.model.structuredefinition.MappingElement; import com.b2international.snowowl.fhir.tests.FhirTest; import io.restassured.path.json.JsonPath; /** * Tests for {@link MappingElement} * @since 8.0.0 */ public class MappingTest extends FhirTest { private Mapping mapping; @Before public void setup() throws Exception { mapping = Mapping.builder() .comment("comment") .identity("identity") .name("name") .uri("uri") .build(); } @Test public void build() throws Exception { validate(mapping); } private void validate(Mapping mapping) { assertEquals("comment", mapping.getComment()); assertEquals("identity", mapping.getIdentity().getIdValue()); assertEquals("name", mapping.getName()); assertEquals("uri", mapping.getUri().getUriValue()); } @Test public void serialize() throws Exception { JsonPath jsonPath = JsonPath.from(objectMapper.writeValueAsString(mapping)); assertThat(jsonPath.getString("comment"), equalTo("comment")); assertThat(jsonPath.getString("identity"), equalTo("identity")); assertThat(jsonPath.getString("name"), equalTo("name")); assertThat(jsonPath.getString("uri"), equalTo("uri")); } @Test public void deserialize() throws Exception { Mapping readMapping = objectMapper.readValue(objectMapper.writeValueAsString(mapping), Mapping.class); validate(readMapping); } }
apache-2.0
V1toss/JavaPA
part_4/consolemenu/src/main/java/vkaretko/actions/About.java
554
package vkaretko.actions; import vkaretko.interfaces.Action; /** * Class About to show information about developers. * * @author Karetko Victor * @version 1.00 * @since 07.12.2016 */ public class About extends Action { /** * Overrided method of execute. * Executes current action. */ @Override public void execute() { System.out.println("HelpAbout"); } /** * Overrided method of getKey. * @return key of action. */ @Override public String getKey() { return "ab"; } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/krms/impl/src/test/java/org/kuali/rice/krms/impl/repository/ReferenceObjectBindingBoServiceImplGenTest.java
6087
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krms.impl.repository; import org.junit.Before; import org.junit.Test; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krms.api.repository.ReferenceObjectBindingGenTest; import org.kuali.rice.krms.api.repository.reference.ReferenceObjectBinding; import static org.mockito.Mockito.*; /** * @author Kuali Rice Team (rice.collab@kuali.org) * */ public final class ReferenceObjectBindingBoServiceImplGenTest { ReferenceObjectBindingBoServiceImpl referenceObjectBindingBoServiceImpl; ReferenceObjectBinding referenceObjectBinding; ReferenceObjectBinding getReferenceObjectBinding() { return referenceObjectBinding; } public void setReferenceObjectBindingBoServiceImpl(ReferenceObjectBindingBoServiceImpl impl) { this.referenceObjectBindingBoServiceImpl = impl; } public static org.kuali.rice.krms.impl.repository.ReferenceObjectBindingBoServiceImplGenTest create(ReferenceObjectBindingBoServiceImpl impl) { org.kuali.rice.krms.impl.repository.ReferenceObjectBindingBoServiceImplGenTest test = new org.kuali.rice.krms.impl.repository.ReferenceObjectBindingBoServiceImplGenTest(); test.setReferenceObjectBindingBoServiceImpl(impl); return test; } @Before public void setUp() { referenceObjectBindingBoServiceImpl = new ReferenceObjectBindingBoServiceImpl(); referenceObjectBindingBoServiceImpl.setBusinessObjectService(mock(BusinessObjectService.class));// TODO Import static org.mockito.Mockito.*; } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByCollectionName_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByCollectionName(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByKrmsDiscriminatorType_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByKrmsDiscriminatorType(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByKrmsObject_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByKrmsObject(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByNamespace_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByNamespace(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByReferenceDiscriminatorType_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByReferenceDiscriminatorType(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_findReferenceObjectBindingsByReferenceObject_null_fail() { referenceObjectBindingBoServiceImpl.findReferenceObjectBindingsByReferenceObject(null); } @Test public void test_from_null_yields_null() { assert(referenceObjectBindingBoServiceImpl.from(null) == null); } @Test public void test_from() { ReferenceObjectBinding def = ReferenceObjectBindingGenTest.buildFullReferenceObjectBinding(); ReferenceObjectBindingBo referenceObjectBindingBo = referenceObjectBindingBoServiceImpl.from(def); assert(referenceObjectBindingBo.getKrmsDiscriminatorType().equals(def.getKrmsDiscriminatorType())); assert(referenceObjectBindingBo.getKrmsObjectId().equals(def.getKrmsObjectId())); assert(referenceObjectBindingBo.getNamespace().equals(def.getNamespace())); assert(referenceObjectBindingBo.getReferenceDiscriminatorType().equals(def.getReferenceDiscriminatorType())); assert(referenceObjectBindingBo.getReferenceObjectId().equals(def.getReferenceObjectId())); assert(referenceObjectBindingBo.getId().equals(def.getId())); } @Test public void test_to() { ReferenceObjectBinding def = ReferenceObjectBindingGenTest.buildFullReferenceObjectBinding(); ReferenceObjectBindingBo referenceObjectBindingBo = referenceObjectBindingBoServiceImpl.from(def); ReferenceObjectBinding def2 = ReferenceObjectBindingBo.to(referenceObjectBindingBo); assert(def.equals(def2)); } @Test public void test_createReferenceObjectBinding() { ReferenceObjectBinding def = ReferenceObjectBindingGenTest.buildFullReferenceObjectBinding(); referenceObjectBinding = referenceObjectBindingBoServiceImpl.createReferenceObjectBinding(def); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_createReferenceObjectBinding_null_fail() { referenceObjectBindingBoServiceImpl.createReferenceObjectBinding(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_updateReferenceObjectBinding_null_fail() { referenceObjectBindingBoServiceImpl.updateReferenceObjectBinding(null); } @Test(expected = java.lang.IllegalArgumentException.class) public void test_deleteReferenceObjectBinding_null_fail() { referenceObjectBindingBoServiceImpl.deleteReferenceObjectBinding(null); } // void create() { // TODO gen // ReferenceObjectBinding def = ReferenceObjectBindingGenTest.buildFullFKReferenceObjectBinding(params); // } }
apache-2.0
haikuowuya/android_system_code
src/com/sun/org/apache/xerces/internal/jaxp/validation/DOMResultBuilder.java
14455
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xerces.internal.jaxp.validation; import java.util.ArrayList; import javax.xml.transform.dom.DOMResult; import com.sun.org.apache.xerces.internal.dom.AttrImpl; import com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl; import com.sun.org.apache.xerces.internal.dom.DOMMessageFormatter; import com.sun.org.apache.xerces.internal.dom.DocumentTypeImpl; import com.sun.org.apache.xerces.internal.dom.ElementImpl; import com.sun.org.apache.xerces.internal.dom.ElementNSImpl; import com.sun.org.apache.xerces.internal.dom.EntityImpl; import com.sun.org.apache.xerces.internal.dom.NotationImpl; import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl; import com.sun.org.apache.xerces.internal.dom.PSVIDocumentImpl; import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; import com.sun.org.apache.xerces.internal.impl.Constants; import com.sun.org.apache.xerces.internal.impl.dv.XSSimpleType; import com.sun.org.apache.xerces.internal.xni.Augmentations; import com.sun.org.apache.xerces.internal.xni.NamespaceContext; import com.sun.org.apache.xerces.internal.xni.QName; import com.sun.org.apache.xerces.internal.xni.XMLAttributes; import com.sun.org.apache.xerces.internal.xni.XMLLocator; import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier; import com.sun.org.apache.xerces.internal.xni.XMLString; import com.sun.org.apache.xerces.internal.xni.XNIException; import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource; import com.sun.org.apache.xerces.internal.xs.AttributePSVI; import com.sun.org.apache.xerces.internal.xs.ElementPSVI; import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Entity; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.Notation; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; /** * <p>DOM result builder.</p> * * @author Michael Glavassevich, IBM */ final class DOMResultBuilder implements DOMDocumentHandler { /** Table for quick check of child insertion. */ private final static int[] kidOK; static { kidOK = new int[13]; kidOK[Node.DOCUMENT_NODE] = 1 << Node.ELEMENT_NODE | 1 << Node.PROCESSING_INSTRUCTION_NODE | 1 << Node.COMMENT_NODE | 1 << Node.DOCUMENT_TYPE_NODE; kidOK[Node.DOCUMENT_FRAGMENT_NODE] = kidOK[Node.ENTITY_NODE] = kidOK[Node.ENTITY_REFERENCE_NODE] = kidOK[Node.ELEMENT_NODE] = 1 << Node.ELEMENT_NODE | 1 << Node.PROCESSING_INSTRUCTION_NODE | 1 << Node.COMMENT_NODE | 1 << Node.TEXT_NODE | 1 << Node.CDATA_SECTION_NODE | 1 << Node.ENTITY_REFERENCE_NODE ; kidOK[Node.ATTRIBUTE_NODE] = 1 << Node.TEXT_NODE | 1 << Node.ENTITY_REFERENCE_NODE; kidOK[Node.DOCUMENT_TYPE_NODE] = 0; kidOK[Node.PROCESSING_INSTRUCTION_NODE] = 0; kidOK[Node.COMMENT_NODE] = 0; kidOK[Node.TEXT_NODE] = 0; kidOK[Node.CDATA_SECTION_NODE] = 0; kidOK[Node.NOTATION_NODE] = 0; } // static // // Data // private Document fDocument; private CoreDocumentImpl fDocumentImpl; private boolean fStorePSVI; private Node fTarget; private Node fNextSibling; private Node fCurrentNode; private Node fFragmentRoot; private final ArrayList fTargetChildren = new ArrayList(); private boolean fIgnoreChars; private final QName fAttributeQName = new QName(); public DOMResultBuilder() {} /* * DOMDocumentHandler methods */ public void setDOMResult(DOMResult result) { fCurrentNode = null; fFragmentRoot = null; fIgnoreChars = false; fTargetChildren.clear(); if (result != null) { fTarget = result.getNode(); fNextSibling = result.getNextSibling(); fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument(); fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null; fStorePSVI = (fDocument instanceof PSVIDocumentImpl); return; } fTarget = null; fNextSibling = null; fDocument = null; fDocumentImpl = null; fStorePSVI = false; } public void doctypeDecl(DocumentType node) throws XNIException { /** Create new DocumentType node for the target. */ if (fDocumentImpl != null) { DocumentType docType = fDocumentImpl.createDocumentType(node.getName(), node.getPublicId(), node.getSystemId()); final String internalSubset = node.getInternalSubset(); /** Copy internal subset. */ if (internalSubset != null) { ((DocumentTypeImpl) docType).setInternalSubset(internalSubset); } /** Copy entities. */ NamedNodeMap oldMap = node.getEntities(); NamedNodeMap newMap = docType.getEntities(); int length = oldMap.getLength(); for (int i = 0; i < length; ++i) { Entity oldEntity = (Entity) oldMap.item(i); EntityImpl newEntity = (EntityImpl) fDocumentImpl.createEntity(oldEntity.getNodeName()); newEntity.setPublicId(oldEntity.getPublicId()); newEntity.setSystemId(oldEntity.getSystemId()); newEntity.setNotationName(oldEntity.getNotationName()); newMap.setNamedItem(newEntity); } /** Copy notations. */ oldMap = node.getNotations(); newMap = docType.getNotations(); length = oldMap.getLength(); for (int i = 0; i < length; ++i) { Notation oldNotation = (Notation) oldMap.item(i); NotationImpl newNotation = (NotationImpl) fDocumentImpl.createNotation(oldNotation.getNodeName()); newNotation.setPublicId(oldNotation.getPublicId()); newNotation.setSystemId(oldNotation.getSystemId()); newMap.setNamedItem(newNotation); } append(docType); } } public void characters(Text node) throws XNIException { /** Create new Text node for the target. */ append(fDocument.createTextNode(node.getNodeValue())); } public void cdata(CDATASection node) throws XNIException { /** Create new CDATASection node for the target. */ append(fDocument.createCDATASection(node.getNodeValue())); } public void comment(Comment node) throws XNIException { /** Create new Comment node for the target. */ append(fDocument.createComment(node.getNodeValue())); } public void processingInstruction(ProcessingInstruction node) throws XNIException { /** Create new ProcessingInstruction node for the target. */ append(fDocument.createProcessingInstruction(node.getTarget(), node.getData())); } public void setIgnoringCharacters(boolean ignore) { fIgnoreChars = ignore; } /* * XMLDocumentHandler methods */ public void startDocument(XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException {} public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException {} public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException {} public void comment(XMLString text, Augmentations augs) throws XNIException {} public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException {} public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Element elem; int attrCount = attributes.getLength(); if (fDocumentImpl == null) { elem = fDocument.createElementNS(element.uri, element.rawname); for (int i = 0; i < attrCount; ++i) { attributes.getName(i, fAttributeQName); elem.setAttributeNS(fAttributeQName.uri, fAttributeQName.rawname, attributes.getValue(i)); } } // If it's a Xerces DOM store type information for attributes, set idness, etc.. else { elem = fDocumentImpl.createElementNS(element.uri, element.rawname, element.localpart); for (int i = 0; i < attrCount; ++i) { attributes.getName(i, fAttributeQName); AttrImpl attr = (AttrImpl) fDocumentImpl.createAttributeNS(fAttributeQName.uri, fAttributeQName.rawname, fAttributeQName.localpart); attr.setValue(attributes.getValue(i)); // write type information to this attribute AttributePSVI attrPSVI = (AttributePSVI) attributes.getAugmentations(i).getItem (Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { if (fStorePSVI) { ((PSVIAttrNSImpl) attr).setPSVI(attrPSVI); } Object type = attrPSVI.getMemberTypeDefinition(); if (type == null) { type = attrPSVI.getTypeDefinition(); if (type != null) { attr.setType (type); if (((XSSimpleType) type).isIDType()) { ((ElementImpl) elem).setIdAttributeNode (attr, true); } } } else { attr.setType (type); if (((XSSimpleType) type).isIDType()) { ((ElementImpl) elem).setIdAttributeNode (attr, true); } } } attr.setSpecified(attributes.isSpecified(i)); elem.setAttributeNode(attr); } } append(elem); fCurrentNode = elem; if (fFragmentRoot == null) { fFragmentRoot = elem; } } public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { startElement(element, attributes, augs); endElement(element, augs); } public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException {} public void textDecl(String version, String encoding, Augmentations augs) throws XNIException {} public void endGeneralEntity(String name, Augmentations augs) throws XNIException {} public void characters(XMLString text, Augmentations augs) throws XNIException { if (!fIgnoreChars) { append(fDocument.createTextNode(text.toString())); } } public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { characters(text, augs); } public void endElement(QName element, Augmentations augs) throws XNIException { // write type information to this element if (augs != null && fDocumentImpl != null) { ElementPSVI elementPSVI = (ElementPSVI)augs.getItem(Constants.ELEMENT_PSVI); if (elementPSVI != null) { if (fStorePSVI) { ((PSVIElementNSImpl)fCurrentNode).setPSVI(elementPSVI); } XSTypeDefinition type = elementPSVI.getMemberTypeDefinition(); if (type == null) { type = elementPSVI.getTypeDefinition(); } ((ElementNSImpl)fCurrentNode).setType(type); } } // adjust current node reference if (fCurrentNode == fFragmentRoot) { fCurrentNode = null; fFragmentRoot = null; return; } fCurrentNode = fCurrentNode.getParentNode(); } public void startCDATA(Augmentations augs) throws XNIException {} public void endCDATA(Augmentations augs) throws XNIException {} public void endDocument(Augmentations augs) throws XNIException { final int length = fTargetChildren.size(); if (fNextSibling == null) { for (int i = 0; i < length; ++i) { fTarget.appendChild((Node) fTargetChildren.get(i)); } } else { for (int i = 0; i < length; ++i) { fTarget.insertBefore((Node) fTargetChildren.get(i), fNextSibling); } } } public void setDocumentSource(XMLDocumentSource source) {} public XMLDocumentSource getDocumentSource() { return null; } /* * Other methods */ private void append(Node node) throws XNIException { if (fCurrentNode != null) { fCurrentNode.appendChild(node); } else { /** Check if this node can be attached to the target. */ if ((kidOK[fTarget.getNodeType()] & (1 << node.getNodeType())) == 0) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null); throw new XNIException(msg); } fTargetChildren.add(node); } } } // DOMResultBuilder
apache-2.0
ahus1/bdd-examples
jgiven-arquillian/src/test/java/de/ahus1/bdd/stage/ThenResultPage.java
710
package de.ahus1.bdd.stage; import com.tngtech.jgiven.CurrentStep; import com.tngtech.jgiven.Stage; import com.tngtech.jgiven.annotation.ExpectedScenarioState; import de.ahus1.bdd.website.ResultPage; import static org.assertj.core.api.Assertions.assertThat; public class ThenResultPage extends Stage<ThenResultPage> { @ExpectedScenarioState private ResultPage resultPage; @ExpectedScenarioState private CurrentStep currentStep; public ThenResultPage the_result_shows_at_least_$_results(int numResults) { assertThat(resultPage.getNumberOfsearchResults()).isGreaterThan(numResults); currentStep.addAttachment(resultPage.createScreenshot()); return this; } }
apache-2.0