repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
joansmith/structr
structr-core/src/main/java/org/structr/schema/parser/NotionPropertyParser.java
5739
/** * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.schema.parser; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.structr.common.error.ErrorBuffer; import org.structr.common.error.FrameworkException; import org.structr.core.property.CollectionNotionProperty; import org.structr.core.property.EntityNotionProperty; import org.structr.schema.Schema; import org.structr.schema.SchemaHelper.Type; /** * * */ public class NotionPropertyParser extends PropertySourceGenerator { private final Set<String> properties = new LinkedHashSet<>(); private boolean isPropertySet = false; private boolean isAutocreate = false; private String parameters = ""; private String propertyType = null; private String relatedType = null; private String baseProperty = null; private String multiplicity = null; public NotionPropertyParser(final ErrorBuffer errorBuffer, final String className, final PropertyDefinition params) { super(errorBuffer, className, params); } @Override public String getPropertyType() { return propertyType; } @Override public String getValueType() { return relatedType; } @Override public String getUnqualifiedValueType() { return relatedType; } @Override public String getPropertyParameters() { return parameters; } @Override public Type getKey() { return Type.Notion; } @Override public void parseFormatString(final Schema entity, String expression) throws FrameworkException { if (StringUtils.isBlank(expression)) { throw new FrameworkException(422, "Notion property expression may not be empty."); } final StringBuilder buf = new StringBuilder(); final String[] parts = expression.split("[, ]+"); if (parts.length > 0) { boolean isBuiltinProperty = false; baseProperty = parts[0]; multiplicity = entity.getMultiplicity(baseProperty); if (multiplicity != null) { // determine related type from relationship relatedType = entity.getRelatedType(baseProperty); switch (multiplicity) { case "1X": // this line exists because when a NotionProperty is set up for a builtin propery // (like for example "owner", there must not be the string "Property" appended // to the property name, and the SchemaNode returns the above "extended" multiplicity // string when it has detected a fallback property name like "owner" from NodeInterface. isBuiltinProperty = true; // no break! case "1": propertyType = EntityNotionProperty.class.getSimpleName(); break; case "*X": // this line exists because when a NotionProperty is set up for a builtin propery // (like for example "owner", there must not be the string "Property" appended // to the property name, and the SchemaNode returns the above "extended" multiplicity // string when it has detected a fallback property name like "owner" from NodeInterface. isBuiltinProperty = true; // no break! case "*": propertyType = CollectionNotionProperty.class.getSimpleName(); break; default: break; } buf.append(", "); buf.append(entity.getClassName()); buf.append("."); buf.append(baseProperty); // append "Property" only if it is NOT a builtin property! if (!isBuiltinProperty) { buf.append("Property"); } buf.append(","); final boolean isBoolean = (parts.length == 3 && ("true".equals(parts[2].toLowerCase()))); isAutocreate = isBoolean; // use PropertyNotion when only a single element is given if (parts.length == 2 || isBoolean) { buf.append(" new PropertyNotion("); isPropertySet = false; } else { buf.append(" new PropertySetNotion("); isPropertySet = true; } for (int i=1; i<parts.length; i++) { String propertyName = parts[i]; String fullPropertyName = propertyName; // remove prefix from full property name if (fullPropertyName.startsWith("_")) { fullPropertyName = fullPropertyName.substring(1); } if (!"true".equals(propertyName.toLowerCase()) && !propertyName.contains(".")) { buf.append(relatedType); buf.append("."); fullPropertyName = relatedType + "." + fullPropertyName; } properties.add(fullPropertyName); if (propertyName.startsWith("_")) { propertyName = propertyName.substring(1) + "Property"; } buf.append(propertyName); if (i < parts.length-1) { buf.append(", "); } } buf.append(")"); } else { // base property not found, most likely in superclass! } } parameters = buf.toString(); } public boolean isPropertySet() { return isPropertySet; } public Set<String> getProperties() { return properties; } public boolean isAutocreate() { return isAutocreate; } public String getBaseProperty() { return baseProperty; } public String getMultiplicity() { return multiplicity; } }
gpl-3.0
WakeRealityDev/incant
storyfinding/src/main/java/com/yrek/ifstd/blorb/FileBlorb.java
1451
package com.yrek.ifstd.blorb; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; public class FileBlorb extends Blorb { private final RandomAccessFile file; public FileBlorb(File file) throws IOException { this.file = new RandomAccessFile(file, "r"); } @Override public void close() throws IOException { file.close(); } @Override protected int readInt() throws IOException { return file.readInt(); } @Override protected long getPosition() throws IOException { return file.getFilePointer(); } @Override protected void seek(long position) throws IOException { file.seek(position); } @Override protected byte[] getChunkContents(long start, int length) throws IOException { file.seek(start); byte[] contents = new byte[length]; file.readFully(contents); return contents; } @Override protected void writeChunk(long start, int length, OutputStream out) throws IOException { file.seek(start); int total = 0; byte[] buffer = new byte[8192]; while (total < length) { int count = file.read(buffer, 0, Math.min(buffer.length, length - total)); if (count < 0) { break; } out.write(buffer, 0, count); total += count; } } }
gpl-3.0
chriskmanx/qmole
QMOLEDEV/escher/src/gnu/x11/RGB.java
22850
package gnu.x11; /** * X RGB. * * Note, following the convention of X specification, these RGB values are * 16-bit, ranging from 0 to 65535, instead of 8-bit (0 to 255) in some * other areas. */ public class RGB { public static final RGB RED = rgb8 (255, 0, 0); public static final RGB SLATE_GREY = rgb8 (112, 128, 144); public static final RGB DIM_GREY = grey (105); public static final RGB GREY = grey (190); public static final RGB GREY64 = grey (163); public static final RGB GREEN = rgb8 (0, 255, 0); public static final RGB BLUE = rgb8 (0, 0, 255); public static final RGB ANTIQUE_WHITE3 = rgb8 (205, 192, 176); public static final RGB JAVA_PRIMARY1 = rgb8 (0x66, 0x66, 0x99); public static final RGB JAVA_PRIMARY2 = rgb8 (0x99, 0x99, 0xcc); public static final RGB JAVA_PRIMARY3 = rgb8 (0xcc, 0xcc, 0xff); public static final RGB JAVA_SECONDARY1 = rgb8 (0x66, 0x66, 0x66); public static final RGB JAVA_SECONDARY2 = rgb8 (0x99, 0x99, 0x99); public static final RGB JAVA_SECONDARY3 = rgb8 (0xcc, 0xcc, 0xcc); public static final RGB JAVA_BLACK = rgb8 (0x00, 0x00, 0x00); public static final RGB JAVA_WHITE = rgb8 (0xff, 0xff, 0xff); private int red, green, blue; public RGB (String spec) { System.out.println ("not implemented"); } public RGB (int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; } public static RGB rgb8 (int red8, int green8, int blue8) { int factor = 0xffff / 0xff; return new RGB (red8*factor, green8*factor, blue8*factor); } public static RGB grey (int level) { return rgb8 (level, level, level); } public static RGB hsv (int hue, float saturation, float value) { // from http://www.cs.rit.edu/~ncs/color/t_convert.html float red = 0, green = 0, blue = 0; if (saturation == 0) // achromatic (grey) red = green = blue = value; else { float h = hue / 60; int sector = (int) Math.floor (h); // sector 0 to 5 float fraction = h - sector; float v = value; float p = value * (1 - saturation); float q = value * (1 - saturation * fraction); float t = value * (1 - saturation * (1 - fraction)); switch (sector) { case 0: red = v; green = t; blue = p; break; case 1: red = q; green = v; blue = p; break; case 2: red = p; green = v; blue = t; break; case 3: red = p; green = q; blue = v; break; case 4: red = t; green = p; blue = v; break; case 5: red = v; green = p; blue = q; break; } } return new RGB ((int) red*0xffff, (int) green*0xffff, (int) blue*0xffff); } public String spec () { System.out.println ("not implemented"); return "unknown"; } public String toString () { return "#RGB [" + red + " " + green + " " + blue + "]"; } // Getters and setters public int getRed() { return red; } public int getGreen() { return green; } public int getBlue() { return blue; } public void setRed(int red) { this.red = red; } public void setGreen(int green) { this.green = green; } public void setBlue(int blue) { this.blue = blue; } } // from `showrgb' // 255 250 250 snow // 248 248 255 ghost white // 248 248 255 GhostWhite // 245 245 245 white smoke // 245 245 245 WhiteSmoke // 220 220 220 gainsboro // 255 250 240 floral white // 255 250 240 FloralWhite // 253 245 230 old lace // 253 245 230 OldLace // 250 240 230 linen // 250 235 215 antique white // 250 235 215 AntiqueWhite // 255 239 213 papaya whip // 255 239 213 PapayaWhip // 255 235 205 blanched almond // 255 235 205 BlanchedAlmond // 255 228 196 bisque // 255 218 185 peach puff // 255 218 185 PeachPuff // 255 222 173 navajo white // 255 222 173 NavajoWhite // 255 228 181 moccasin // 255 248 220 cornsilk // 255 255 240 ivory // 255 250 205 lemon chiffon // 255 250 205 LemonChiffon // 255 245 238 seashell // 240 255 240 honeydew // 245 255 250 mint cream // 245 255 250 MintCream // 240 255 255 azure // 240 248 255 alice blue // 240 248 255 AliceBlue // 230 230 250 lavender // 255 240 245 lavender blush // 255 240 245 LavenderBlush // 255 228 225 misty rose // 255 228 225 MistyRose // 255 255 255 white // 0 0 0 black // 47 79 79 dark slate gray // 47 79 79 DarkSlateGray // 47 79 79 dark slate grey // 47 79 79 DarkSlateGrey // 105 105 105 dim gray // 105 105 105 DimGray // 105 105 105 dim grey // 105 105 105 DimGrey // 112 128 144 slate gray // 112 128 144 SlateGray // 112 128 144 slate grey // 112 128 144 SlateGrey // 119 136 153 light slate gray // 119 136 153 LightSlateGray // 119 136 153 light slate grey // 119 136 153 LightSlateGrey // 190 190 190 gray // 190 190 190 grey // 211 211 211 light grey // 211 211 211 LightGrey // 211 211 211 light gray // 211 211 211 LightGray // 25 25 112 midnight blue // 25 25 112 MidnightBlue // 0 0 128 navy // 0 0 128 navy blue // 0 0 128 NavyBlue // 100 149 237 cornflower blue // 100 149 237 CornflowerBlue // 72 61 139 dark slate blue // 72 61 139 DarkSlateBlue // 106 90 205 slate blue // 106 90 205 SlateBlue // 123 104 238 medium slate blue // 123 104 238 MediumSlateBlue // 132 112 255 light slate blue // 132 112 255 LightSlateBlue // 0 0 205 medium blue // 0 0 205 MediumBlue // 65 105 225 royal blue // 65 105 225 RoyalBlue // 0 0 255 blue // 30 144 255 dodger blue // 30 144 255 DodgerBlue // 0 191 255 deep sky blue // 0 191 255 DeepSkyBlue // 135 206 235 sky blue // 135 206 235 SkyBlue // 135 206 250 light sky blue // 135 206 250 LightSkyBlue // 70 130 180 steel blue // 70 130 180 SteelBlue // 176 196 222 light steel blue // 176 196 222 LightSteelBlue // 173 216 230 light blue // 173 216 230 LightBlue // 176 224 230 powder blue // 176 224 230 PowderBlue // 175 238 238 pale turquoise // 175 238 238 PaleTurquoise // 0 206 209 dark turquoise // 0 206 209 DarkTurquoise // 72 209 204 medium turquoise // 72 209 204 MediumTurquoise // 64 224 208 turquoise // 0 255 255 cyan // 224 255 255 light cyan // 224 255 255 LightCyan // 95 158 160 cadet blue // 95 158 160 CadetBlue // 102 205 170 medium aquamarine // 102 205 170 MediumAquamarine // 127 255 212 aquamarine // 0 100 0 dark green // 0 100 0 DarkGreen // 85 107 47 dark olive green // 85 107 47 DarkOliveGreen // 143 188 143 dark sea green // 143 188 143 DarkSeaGreen // 46 139 87 sea green // 46 139 87 SeaGreen // 60 179 113 medium sea green // 60 179 113 MediumSeaGreen // 32 178 170 light sea green // 32 178 170 LightSeaGreen // 152 251 152 pale green // 152 251 152 PaleGreen // 0 255 127 spring green // 0 255 127 SpringGreen // 124 252 0 lawn green // 124 252 0 LawnGreen // 0 255 0 green // 127 255 0 chartreuse // 0 250 154 medium spring green // 0 250 154 MediumSpringGreen // 173 255 47 green yellow // 173 255 47 GreenYellow // 50 205 50 lime green // 50 205 50 LimeGreen // 154 205 50 yellow green // 154 205 50 YellowGreen // 34 139 34 forest green // 34 139 34 ForestGreen // 107 142 35 olive drab // 107 142 35 OliveDrab // 189 183 107 dark khaki // 189 183 107 DarkKhaki // 240 230 140 khaki // 238 232 170 pale goldenrod // 238 232 170 PaleGoldenrod // 250 250 210 light goldenrod yellow // 250 250 210 LightGoldenrodYellow // 255 255 224 light yellow // 255 255 224 LightYellow // 255 255 0 yellow // 255 215 0 gold // 238 221 130 light goldenrod // 238 221 130 LightGoldenrod // 218 165 32 goldenrod // 184 134 11 dark goldenrod // 184 134 11 DarkGoldenrod // 188 143 143 rosy brown // 188 143 143 RosyBrown // 205 92 92 indian red // 205 92 92 IndianRed // 139 69 19 saddle brown // 139 69 19 SaddleBrown // 160 82 45 sienna // 205 133 63 peru // 222 184 135 burlywood // 245 245 220 beige // 245 222 179 wheat // 244 164 96 sandy brown // 244 164 96 SandyBrown // 210 180 140 tan // 210 105 30 chocolate // 178 34 34 firebrick // 165 42 42 brown // 233 150 122 dark salmon // 233 150 122 DarkSalmon // 250 128 114 salmon // 255 160 122 light salmon // 255 160 122 LightSalmon // 255 165 0 orange // 255 140 0 dark orange // 255 140 0 DarkOrange // 255 127 80 coral // 240 128 128 light coral // 240 128 128 LightCoral // 255 99 71 tomato // 255 69 0 orange red // 255 69 0 OrangeRed // 255 0 0 red // 255 105 180 hot pink // 255 105 180 HotPink // 255 20 147 deep pink // 255 20 147 DeepPink // 255 192 203 pink // 255 182 193 light pink // 255 182 193 LightPink // 219 112 147 pale violet red // 219 112 147 PaleVioletRed // 176 48 96 maroon // 199 21 133 medium violet red // 199 21 133 MediumVioletRed // 208 32 144 violet red // 208 32 144 VioletRed // 255 0 255 magenta // 238 130 238 violet // 221 160 221 plum // 218 112 214 orchid // 186 85 211 medium orchid // 186 85 211 MediumOrchid // 153 50 204 dark orchid // 153 50 204 DarkOrchid // 148 0 211 dark violet // 148 0 211 DarkViolet // 138 43 226 blue violet // 138 43 226 BlueViolet // 160 32 240 purple // 147 112 219 medium purple // 147 112 219 MediumPurple // 216 191 216 thistle // 255 250 250 snow1 // 238 233 233 snow2 // 205 201 201 snow3 // 139 137 137 snow4 // 255 245 238 seashell1 // 238 229 222 seashell2 // 205 197 191 seashell3 // 139 134 130 seashell4 // 255 239 219 AntiqueWhite1 // 238 223 204 AntiqueWhite2 // 205 192 176 AntiqueWhite3 // 139 131 120 AntiqueWhite4 // 255 228 196 bisque1 // 238 213 183 bisque2 // 205 183 158 bisque3 // 139 125 107 bisque4 // 255 218 185 PeachPuff1 // 238 203 173 PeachPuff2 // 205 175 149 PeachPuff3 // 139 119 101 PeachPuff4 // 255 222 173 NavajoWhite1 // 238 207 161 NavajoWhite2 // 205 179 139 NavajoWhite3 // 139 121 94 NavajoWhite4 // 255 250 205 LemonChiffon1 // 238 233 191 LemonChiffon2 // 205 201 165 LemonChiffon3 // 139 137 112 LemonChiffon4 // 255 248 220 cornsilk1 // 238 232 205 cornsilk2 // 205 200 177 cornsilk3 // 139 136 120 cornsilk4 // 255 255 240 ivory1 // 238 238 224 ivory2 // 205 205 193 ivory3 // 139 139 131 ivory4 // 240 255 240 honeydew1 // 224 238 224 honeydew2 // 193 205 193 honeydew3 // 131 139 131 honeydew4 // 255 240 245 LavenderBlush1 // 238 224 229 LavenderBlush2 // 205 193 197 LavenderBlush3 // 139 131 134 LavenderBlush4 // 255 228 225 MistyRose1 // 238 213 210 MistyRose2 // 205 183 181 MistyRose3 // 139 125 123 MistyRose4 // 240 255 255 azure1 // 224 238 238 azure2 // 193 205 205 azure3 // 131 139 139 azure4 // 131 111 255 SlateBlue1 // 122 103 238 SlateBlue2 // 105 89 205 SlateBlue3 // 71 60 139 SlateBlue4 // 72 118 255 RoyalBlue1 // 67 110 238 RoyalBlue2 // 58 95 205 RoyalBlue3 // 39 64 139 RoyalBlue4 // 0 0 255 blue1 // 0 0 238 blue2 // 0 0 205 blue3 // 0 0 139 blue4 // 30 144 255 DodgerBlue1 // 28 134 238 DodgerBlue2 // 24 116 205 DodgerBlue3 // 16 78 139 DodgerBlue4 // 99 184 255 SteelBlue1 // 92 172 238 SteelBlue2 // 79 148 205 SteelBlue3 // 54 100 139 SteelBlue4 // 0 191 255 DeepSkyBlue1 // 0 178 238 DeepSkyBlue2 // 0 154 205 DeepSkyBlue3 // 0 104 139 DeepSkyBlue4 // 135 206 255 SkyBlue1 // 126 192 238 SkyBlue2 // 108 166 205 SkyBlue3 // 74 112 139 SkyBlue4 // 176 226 255 LightSkyBlue1 // 164 211 238 LightSkyBlue2 // 141 182 205 LightSkyBlue3 // 96 123 139 LightSkyBlue4 // 198 226 255 SlateGray1 // 185 211 238 SlateGray2 // 159 182 205 SlateGray3 // 108 123 139 SlateGray4 // 202 225 255 LightSteelBlue1 // 188 210 238 LightSteelBlue2 // 162 181 205 LightSteelBlue3 // 110 123 139 LightSteelBlue4 // 191 239 255 LightBlue1 // 178 223 238 LightBlue2 // 154 192 205 LightBlue3 // 104 131 139 LightBlue4 // 224 255 255 LightCyan1 // 209 238 238 LightCyan2 // 180 205 205 LightCyan3 // 122 139 139 LightCyan4 // 187 255 255 PaleTurquoise1 // 174 238 238 PaleTurquoise2 // 150 205 205 PaleTurquoise3 // 102 139 139 PaleTurquoise4 // 152 245 255 CadetBlue1 // 142 229 238 CadetBlue2 // 122 197 205 CadetBlue3 // 83 134 139 CadetBlue4 // 0 245 255 turquoise1 // 0 229 238 turquoise2 // 0 197 205 turquoise3 // 0 134 139 turquoise4 // 0 255 255 cyan1 // 0 238 238 cyan2 // 0 205 205 cyan3 // 0 139 139 cyan4 // 151 255 255 DarkSlateGray1 // 141 238 238 DarkSlateGray2 // 121 205 205 DarkSlateGray3 // 82 139 139 DarkSlateGray4 // 127 255 212 aquamarine1 // 118 238 198 aquamarine2 // 102 205 170 aquamarine3 // 69 139 116 aquamarine4 // 193 255 193 DarkSeaGreen1 // 180 238 180 DarkSeaGreen2 // 155 205 155 DarkSeaGreen3 // 105 139 105 DarkSeaGreen4 // 84 255 159 SeaGreen1 // 78 238 148 SeaGreen2 // 67 205 128 SeaGreen3 // 46 139 87 SeaGreen4 // 154 255 154 PaleGreen1 // 144 238 144 PaleGreen2 // 124 205 124 PaleGreen3 // 84 139 84 PaleGreen4 // 0 255 127 SpringGreen1 // 0 238 118 SpringGreen2 // 0 205 102 SpringGreen3 // 0 139 69 SpringGreen4 // 0 255 0 green1 // 0 238 0 green2 // 0 205 0 green3 // 0 139 0 green4 // 127 255 0 chartreuse1 // 118 238 0 chartreuse2 // 102 205 0 chartreuse3 // 69 139 0 chartreuse4 // 192 255 62 OliveDrab1 // 179 238 58 OliveDrab2 // 154 205 50 OliveDrab3 // 105 139 34 OliveDrab4 // 202 255 112 DarkOliveGreen1 // 188 238 104 DarkOliveGreen2 // 162 205 90 DarkOliveGreen3 // 110 139 61 DarkOliveGreen4 // 255 246 143 khaki1 // 238 230 133 khaki2 // 205 198 115 khaki3 // 139 134 78 khaki4 // 255 236 139 LightGoldenrod1 // 238 220 130 LightGoldenrod2 // 205 190 112 LightGoldenrod3 // 139 129 76 LightGoldenrod4 // 255 255 224 LightYellow1 // 238 238 209 LightYellow2 // 205 205 180 LightYellow3 // 139 139 122 LightYellow4 // 255 255 0 yellow1 // 238 238 0 yellow2 // 205 205 0 yellow3 // 139 139 0 yellow4 // 255 215 0 gold1 // 238 201 0 gold2 // 205 173 0 gold3 // 139 117 0 gold4 // 255 193 37 goldenrod1 // 238 180 34 goldenrod2 // 205 155 29 goldenrod3 // 139 105 20 goldenrod4 // 255 185 15 DarkGoldenrod1 // 238 173 14 DarkGoldenrod2 // 205 149 12 DarkGoldenrod3 // 139 101 8 DarkGoldenrod4 // 255 193 193 RosyBrown1 // 238 180 180 RosyBrown2 // 205 155 155 RosyBrown3 // 139 105 105 RosyBrown4 // 255 106 106 IndianRed1 // 238 99 99 IndianRed2 // 205 85 85 IndianRed3 // 139 58 58 IndianRed4 // 255 130 71 sienna1 // 238 121 66 sienna2 // 205 104 57 sienna3 // 139 71 38 sienna4 // 255 211 155 burlywood1 // 238 197 145 burlywood2 // 205 170 125 burlywood3 // 139 115 85 burlywood4 // 255 231 186 wheat1 // 238 216 174 wheat2 // 205 186 150 wheat3 // 139 126 102 wheat4 // 255 165 79 tan1 // 238 154 73 tan2 // 205 133 63 tan3 // 139 90 43 tan4 // 255 127 36 chocolate1 // 238 118 33 chocolate2 // 205 102 29 chocolate3 // 139 69 19 chocolate4 // 255 48 48 firebrick1 // 238 44 44 firebrick2 // 205 38 38 firebrick3 // 139 26 26 firebrick4 // 255 64 64 brown1 // 238 59 59 brown2 // 205 51 51 brown3 // 139 35 35 brown4 // 255 140 105 salmon1 // 238 130 98 salmon2 // 205 112 84 salmon3 // 139 76 57 salmon4 // 255 160 122 LightSalmon1 // 238 149 114 LightSalmon2 // 205 129 98 LightSalmon3 // 139 87 66 LightSalmon4 // 255 165 0 orange1 // 238 154 0 orange2 // 205 133 0 orange3 // 139 90 0 orange4 // 255 127 0 DarkOrange1 // 238 118 0 DarkOrange2 // 205 102 0 DarkOrange3 // 139 69 0 DarkOrange4 // 255 114 86 coral1 // 238 106 80 coral2 // 205 91 69 coral3 // 139 62 47 coral4 // 255 99 71 tomato1 // 238 92 66 tomato2 // 205 79 57 tomato3 // 139 54 38 tomato4 // 255 69 0 OrangeRed1 // 238 64 0 OrangeRed2 // 205 55 0 OrangeRed3 // 139 37 0 OrangeRed4 // 255 0 0 red1 // 238 0 0 red2 // 205 0 0 red3 // 139 0 0 red4 // 255 20 147 DeepPink1 // 238 18 137 DeepPink2 // 205 16 118 DeepPink3 // 139 10 80 DeepPink4 // 255 110 180 HotPink1 // 238 106 167 HotPink2 // 205 96 144 HotPink3 // 139 58 98 HotPink4 // 255 181 197 pink1 // 238 169 184 pink2 // 205 145 158 pink3 // 139 99 108 pink4 // 255 174 185 LightPink1 // 238 162 173 LightPink2 // 205 140 149 LightPink3 // 139 95 101 LightPink4 // 255 130 171 PaleVioletRed1 // 238 121 159 PaleVioletRed2 // 205 104 137 PaleVioletRed3 // 139 71 93 PaleVioletRed4 // 255 52 179 maroon1 // 238 48 167 maroon2 // 205 41 144 maroon3 // 139 28 98 maroon4 // 255 62 150 VioletRed1 // 238 58 140 VioletRed2 // 205 50 120 VioletRed3 // 139 34 82 VioletRed4 // 255 0 255 magenta1 // 238 0 238 magenta2 // 205 0 205 magenta3 // 139 0 139 magenta4 // 255 131 250 orchid1 // 238 122 233 orchid2 // 205 105 201 orchid3 // 139 71 137 orchid4 // 255 187 255 plum1 // 238 174 238 plum2 // 205 150 205 plum3 // 139 102 139 plum4 // 224 102 255 MediumOrchid1 // 209 95 238 MediumOrchid2 // 180 82 205 MediumOrchid3 // 122 55 139 MediumOrchid4 // 191 62 255 DarkOrchid1 // 178 58 238 DarkOrchid2 // 154 50 205 DarkOrchid3 // 104 34 139 DarkOrchid4 // 155 48 255 purple1 // 145 44 238 purple2 // 125 38 205 purple3 // 85 26 139 purple4 // 171 130 255 MediumPurple1 // 159 121 238 MediumPurple2 // 137 104 205 MediumPurple3 // 93 71 139 MediumPurple4 // 255 225 255 thistle1 // 238 210 238 thistle2 // 205 181 205 thistle3 // 139 123 139 thistle4 // 0 0 0 gray0 // 0 0 0 grey0 // 3 3 3 gray1 // 3 3 3 grey1 // 5 5 5 gray2 // 5 5 5 grey2 // 8 8 8 gray3 // 8 8 8 grey3 // 10 10 10 gray4 // 10 10 10 grey4 // 13 13 13 gray5 // 13 13 13 grey5 // 15 15 15 gray6 // 15 15 15 grey6 // 18 18 18 gray7 // 18 18 18 grey7 // 20 20 20 gray8 // 20 20 20 grey8 // 23 23 23 gray9 // 23 23 23 grey9 // 26 26 26 gray10 // 26 26 26 grey10 // 28 28 28 gray11 // 28 28 28 grey11 // 31 31 31 gray12 // 31 31 31 grey12 // 33 33 33 gray13 // 33 33 33 grey13 // 36 36 36 gray14 // 36 36 36 grey14 // 38 38 38 gray15 // 38 38 38 grey15 // 41 41 41 gray16 // 41 41 41 grey16 // 43 43 43 gray17 // 43 43 43 grey17 // 46 46 46 gray18 // 46 46 46 grey18 // 48 48 48 gray19 // 48 48 48 grey19 // 51 51 51 gray20 // 51 51 51 grey20 // 54 54 54 gray21 // 54 54 54 grey21 // 56 56 56 gray22 // 56 56 56 grey22 // 59 59 59 gray23 // 59 59 59 grey23 // 61 61 61 gray24 // 61 61 61 grey24 // 64 64 64 gray25 // 64 64 64 grey25 // 66 66 66 gray26 // 66 66 66 grey26 // 69 69 69 gray27 // 69 69 69 grey27 // 71 71 71 gray28 // 71 71 71 grey28 // 74 74 74 gray29 // 74 74 74 grey29 // 77 77 77 gray30 // 77 77 77 grey30 // 79 79 79 gray31 // 79 79 79 grey31 // 82 82 82 gray32 // 82 82 82 grey32 // 84 84 84 gray33 // 84 84 84 grey33 // 87 87 87 gray34 // 87 87 87 grey34 // 89 89 89 gray35 // 89 89 89 grey35 // 92 92 92 gray36 // 92 92 92 grey36 // 94 94 94 gray37 // 94 94 94 grey37 // 97 97 97 gray38 // 97 97 97 grey38 // 99 99 99 gray39 // 99 99 99 grey39 // 102 102 102 gray40 // 102 102 102 grey40 // 105 105 105 gray41 // 105 105 105 grey41 // 107 107 107 gray42 // 107 107 107 grey42 // 110 110 110 gray43 // 110 110 110 grey43 // 112 112 112 gray44 // 112 112 112 grey44 // 115 115 115 gray45 // 115 115 115 grey45 // 117 117 117 gray46 // 117 117 117 grey46 // 120 120 120 gray47 // 120 120 120 grey47 // 122 122 122 gray48 // 122 122 122 grey48 // 125 125 125 gray49 // 125 125 125 grey49 // 127 127 127 gray50 // 127 127 127 grey50 // 130 130 130 gray51 // 130 130 130 grey51 // 133 133 133 gray52 // 133 133 133 grey52 // 135 135 135 gray53 // 135 135 135 grey53 // 138 138 138 gray54 // 138 138 138 grey54 // 140 140 140 gray55 // 140 140 140 grey55 // 143 143 143 gray56 // 143 143 143 grey56 // 145 145 145 gray57 // 145 145 145 grey57 // 148 148 148 gray58 // 148 148 148 grey58 // 150 150 150 gray59 // 150 150 150 grey59 // 153 153 153 gray60 // 153 153 153 grey60 // 156 156 156 gray61 // 156 156 156 grey61 // 158 158 158 gray62 // 158 158 158 grey62 // 161 161 161 gray63 // 161 161 161 grey63 // 163 163 163 gray64 // 163 163 163 grey64 // 166 166 166 gray65 // 166 166 166 grey65 // 168 168 168 gray66 // 168 168 168 grey66 // 171 171 171 gray67 // 171 171 171 grey67 // 173 173 173 gray68 // 173 173 173 grey68 // 176 176 176 gray69 // 176 176 176 grey69 // 179 179 179 gray70 // 179 179 179 grey70 // 181 181 181 gray71 // 181 181 181 grey71 // 184 184 184 gray72 // 184 184 184 grey72 // 186 186 186 gray73 // 186 186 186 grey73 // 189 189 189 gray74 // 189 189 189 grey74 // 191 191 191 gray75 // 191 191 191 grey75 // 194 194 194 gray76 // 194 194 194 grey76 // 196 196 196 gray77 // 196 196 196 grey77 // 199 199 199 gray78 // 199 199 199 grey78 // 201 201 201 gray79 // 201 201 201 grey79 // 204 204 204 gray80 // 204 204 204 grey80 // 207 207 207 gray81 // 207 207 207 grey81 // 209 209 209 gray82 // 209 209 209 grey82 // 212 212 212 gray83 // 212 212 212 grey83 // 214 214 214 gray84 // 214 214 214 grey84 // 217 217 217 gray85 // 217 217 217 grey85 // 219 219 219 gray86 // 219 219 219 grey86 // 222 222 222 gray87 // 222 222 222 grey87 // 224 224 224 gray88 // 224 224 224 grey88 // 227 227 227 gray89 // 227 227 227 grey89 // 229 229 229 gray90 // 229 229 229 grey90 // 232 232 232 gray91 // 232 232 232 grey91 // 235 235 235 gray92 // 235 235 235 grey92 // 237 237 237 gray93 // 237 237 237 grey93 // 240 240 240 gray94 // 240 240 240 grey94 // 242 242 242 gray95 // 242 242 242 grey95 // 245 245 245 gray96 // 245 245 245 grey96 // 247 247 247 gray97 // 247 247 247 grey97 // 250 250 250 gray98 // 250 250 250 grey98 // 252 252 252 gray99 // 252 252 252 grey99 // 255 255 255 gray100 // 255 255 255 grey100 // 169 169 169 dark grey // 169 169 169 DarkGrey // 169 169 169 dark gray // 169 169 169 DarkGray // 0 0 139 dark blue // 0 0 139 DarkBlue // 0 139 139 dark cyan // 0 139 139 DarkCyan // 139 0 139 dark magenta // 139 0 139 DarkMagenta // 139 0 0 dark red // 139 0 0 DarkRed // 144 238 144 light green // 144 238 144 LightGreen // cr610941-a:~/code/gnu/tk#
gpl-3.0
scrudden/core
transitime/src/main/java/org/transitime/core/AvlProcessor.java
62470
/* * This file is part of Transitime.org * * Transitime.org is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPL) as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Transitime.org 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 Transitime.org . If not, see <http://www.gnu.org/licenses/>. */ package org.transitime.core; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.transitime.applications.Core; import org.transitime.config.BooleanConfigValue; import org.transitime.config.DoubleConfigValue; import org.transitime.config.IntegerConfigValue; import org.transitime.configData.AgencyConfig; import org.transitime.configData.AvlConfig; import org.transitime.configData.CoreConfig; import org.transitime.core.SpatialMatcher.MatchingType; import org.transitime.core.autoAssigner.AutoBlockAssigner; import org.transitime.core.dataCache.PredictionDataCache; import org.transitime.core.dataCache.VehicleDataCache; import org.transitime.core.dataCache.VehicleStateManager; import org.transitime.db.structs.AvlReport; import org.transitime.db.structs.Block; import org.transitime.db.structs.Location; import org.transitime.db.structs.Route; import org.transitime.db.structs.Stop; import org.transitime.db.structs.Trip; import org.transitime.db.structs.VehicleEvent; import org.transitime.db.structs.AvlReport.AssignmentType; import org.transitime.logging.Markers; import org.transitime.utils.Geo; import org.transitime.utils.IntervalTimer; import org.transitime.utils.StringUtils; import org.transitime.utils.Time; /** * This is a very important high-level class. It takes the AVL data and * processes it. Matches vehicles to their assignments. Once a match is made * then MatchProcessor class is used to generate predictions, arrival/departure * times, headway, etc. * * @author SkiBu Smith * */ public class AvlProcessor { // For keeping track of how long since received an AVL report so // can determine if AVL feed is up. private AvlReport lastRegularReportProcessed; // Singleton class private static AvlProcessor singleton = new AvlProcessor(); /*********** Configurable Parameters for this module ***********/ private static double getTerminalDistanceForRouteMatching() { return terminalDistanceForRouteMatching.getValue(); } private static DoubleConfigValue terminalDistanceForRouteMatching = new DoubleConfigValue( "transitime.core.terminalDistanceForRouteMatching", 100.0, "How far vehicle must be away from the terminal before doing " + "initial matching. This is important because when vehicle is at " + "terminal don't know which trip it it should be matched to until " + "vehicle has left the terminal."); private static IntegerConfigValue allowableBadAssignments = new IntegerConfigValue( "transitime.core.allowableBadAssignments", 0, "If get a bad assignment, such as no assignment, but no " + "more than allowableBadAssignments then will use the " + "previous assignment. Useful for when assignment part " + "of AVL feed doesn't always provide a valid assignment."); private static BooleanConfigValue emailMessagesWhenAssignmentGrabImproper = new BooleanConfigValue( "transitime.core.emailMessagesWhenAssignmentGrabImproper", false, "When one vehicle gets assigned by AVL feed but another " + "vehicle already has that assignment then sometimes the " + "assignment to the new vehicle would be incorrect. Could " + "be that vehicle was never logged out or simply got bad " + "assignment. For this situation it can be useful to " + "receive error message via e-mail. But can get too many " + "such e-mails. This property allows one to control those " + "e-mails."); private static DoubleConfigValue maxDistanceForAssignmentGrab = new DoubleConfigValue( "transitime.core.maxDistanceForAssignmentGrab", 10000.0, "For when another vehicles gets assignment and needs to " + "grab it from another vehicle. The new vehicle must " + "match to route within maxDistanceForAssignmentGrab in " + "order to grab the assignment."); /************************** Logging *******************************/ private static final Logger logger = LoggerFactory .getLogger(AvlProcessor.class); /********************** Member Functions **************************/ /* * Singleton class so shouldn't use constructor so declared private */ private AvlProcessor() { } /** * Returns the singleton AvlProcessor * * @return */ public static AvlProcessor getInstance() { return singleton; } /** * Removes predictions and the match for the vehicle and marks it as * unpredictable. Updates VehicleDataCache. Creates and logs a VehicleEvent * explaining the situation. * * @param vehicleId * The vehicle to be made unpredictable * @param eventDescription * A longer description of why vehicle being made unpredictable * @param vehicleEvent * A short description from VehicleEvent class for labeling the * event. */ public void makeVehicleUnpredictable(String vehicleId, String eventDescription, String vehicleEvent) { logger.info("Making vehicleId={} unpredictable. {}", vehicleId, eventDescription); VehicleState vehicleState = VehicleStateManager.getInstance() .getVehicleState(vehicleId); // Create a VehicleEvent to record what happened AvlReport avlReport = vehicleState.getAvlReport(); TemporalMatch lastMatch = vehicleState.getMatch(); boolean wasPredictable = vehicleState.isPredictable(); VehicleEvent.create(avlReport, lastMatch, vehicleEvent, eventDescription, false, // predictable wasPredictable, // becameUnpredictable null); // supervisor // Update the state of the vehicle vehicleState.setMatch(null); // Remove the predictions that were generated by the vehicle PredictionDataCache.getInstance().removePredictions(vehicleState); // Update VehicleDataCache with the new state for the vehicle VehicleDataCache.getInstance().updateVehicle(vehicleState); } /** * Removes predictions and the match for the vehicle and marks is as * unpredictable. Also removes block assignment from the vehicleState. To be * used for situations such as assignment ended or vehicle was reassigned. * Creates and logs a VehicleEvent explaining the situation. * * @param vehicleState * The vehicle to be made unpredictable * @param eventDescription * A longer description of why vehicle being made unpredictable * @param vehicleEvent * A short description from VehicleEvent class for labeling the * event. */ public void makeVehicleUnpredictableAndTerminateAssignment( VehicleState vehicleState, String eventDescription, String vehicleEvent) { makeVehicleUnpredictable(vehicleState.getVehicleId(), eventDescription, vehicleEvent); vehicleState.unsetBlock(BlockAssignmentMethod.ASSIGNMENT_TERMINATED); } /** * Marks the vehicle as not being predictable and that the assignment has * been grabbed. Updates VehicleDataCache. Creates and logs a VehicleEvent * explaining the situation. * * @param vehicleState * The vehicle to be made unpredictable * @param eventDescription * A longer description of why vehicle being made unpredictable * @param vehicleEvent * A short description from VehicleEvent class for labeling the * event. */ public void makeVehicleUnpredictableAndGrabAssignment( VehicleState vehicleState, String eventDescription, String vehicleEvent) { makeVehicleUnpredictable(vehicleState.getVehicleId(), eventDescription, vehicleEvent); vehicleState.unsetBlock(BlockAssignmentMethod.ASSIGNMENT_GRABBED); } /** * Looks at the previous AVL reports to determine if vehicle is actually * moving. If it is not moving then the vehicle is made unpredictable. Uses * the system properties transitime.core.timeForDeterminingNoProgress and * transitime.core.minDistanceForNoProgress * * @param bestTemporalMatch * @param vehicleState * @return True if vehicle not making progress, otherwise false. If vehicle * doesn't currently match or if there is not enough history for the * vehicle then false is returned. */ private boolean handleIfVehicleNotMakingProgress( TemporalMatch bestTemporalMatch, VehicleState vehicleState) { // If there is no current match anyways then don't need to do anything // here. if (bestTemporalMatch == null) return false; // If this feature disabled then return false int noProgressMsec = CoreConfig.getTimeForDeterminingNoProgress(); if (noProgressMsec <= 0) return false; // If no previous match then cannot determine if not making progress TemporalMatch previousMatch = vehicleState.getPreviousMatch(noProgressMsec); if (previousMatch == null) return false; // Determine distance traveled between the matches double distanceTraveled = previousMatch .distanceBetweenMatches(bestTemporalMatch); double minDistance = CoreConfig.getMinDistanceForNoProgress(); if (distanceTraveled < minDistance) { // Determine if went through any wait stops since if did then // vehicle wasn't stuck in traffic. It was simply stopped at // layover. boolean traversedWaitStop = previousMatch .traversedWaitStop(bestTemporalMatch); if (!traversedWaitStop) { // Determine how much time elapsed between AVL reports long timeBetweenAvlReports = vehicleState.getAvlReport().getTime() - previousMatch.getAvlTime(); // Create message indicating why vehicle being made // unpredictable because vehicle not making forward progress. String eventDescription = "Vehicle only traveled " + StringUtils.distanceFormat(distanceTraveled) + " over the last " + Time.elapsedTimeStr(timeBetweenAvlReports) + " which is below minDistanceForNoProgress of " + StringUtils.distanceFormat(minDistance) + " so was made unpredictable."; // Make vehicle unpredictable and do associated logging AvlProcessor.getInstance().makeVehicleUnpredictable( vehicleState.getVehicleId(), eventDescription, VehicleEvent.NO_PROGRESS); // Return that vehicle indeed not making progress return true; } } // Vehicle was making progress so return such return false; } /** * Looks at the previous AVL reports to determine if vehicle is actually * moving. If it is not moving then the vehicle should be marked as being * delayed. Uses the system properties * transitime.core.timeForDeterminingDelayed and * transitime.core.minDistanceForDelayed * * @param vehicleState * For providing the temporal match and the AVL history. It is * expected that the new match has already been set. * @return True if vehicle not making progress, otherwise false. If vehicle * doesn't currently match or if there is not enough history for the * vehicle then false is returned. */ private boolean handlePossibleVehicleDelay(VehicleState vehicleState) { // Assume vehicle is not delayed boolean wasDelayed = vehicleState.isDelayed(); vehicleState.setIsDelayed(false); // Determine the new match TemporalMatch currentMatch = vehicleState.getMatch(); // If there is no current match anyways then don't need to do anything // here. if (currentMatch == null) return false; // If this feature disabled then return false int maxDelayedSecs = CoreConfig.getTimeForDeterminingDelayedSecs(); if (maxDelayedSecs <= 0) return false; // If no previous match then cannot determine if not making progress TemporalMatch previousMatch = vehicleState.getPreviousMatch(maxDelayedSecs * Time.MS_PER_SEC); if (previousMatch == null) return false; // Determine distance traveled between the matches double distanceTraveled = previousMatch .distanceBetweenMatches(currentMatch); double minDistance = CoreConfig.getMinDistanceForDelayed(); if (distanceTraveled < minDistance) { // Determine if went through any wait stops since if did then // vehicle wasn't stuck in traffic. It was simply stopped at // layover. boolean traversedWaitStop = previousMatch .traversedWaitStop(currentMatch); if (!traversedWaitStop) { // Mark vehicle as being delayed vehicleState.setIsDelayed(true); // Create description of event long timeBetweenAvlReports = vehicleState.getAvlReport().getTime() - previousMatch.getAvlTime(); String description = "Vehicle vehicleId=" + vehicleState.getVehicleId() + " is delayed. Over " + timeBetweenAvlReports + " msec it " + "traveled only " + Geo.distanceFormat(distanceTraveled) + " while " + "transitime.core.timeForDeterminingDelayedSecs=" + maxDelayedSecs + " and " + "transitime.core.minDistanceForDelayed=" + Geo.distanceFormat(minDistance); // Log the event logger.info(description); // If vehicle newly delayed then also create a VehicleEvent // indicating such if (!wasDelayed) { VehicleEvent.create(vehicleState.getAvlReport(), vehicleState.getMatch(), VehicleEvent.DELAYED, description, true, // predictable false, // becameUnpredictable null); // supervisor } // Return that vehicle indeed delayed return true; } } // Vehicle was making progress so return such return false; } /** * For vehicles that were already predictable but then got a new AvlReport. * Determines where in the block assignment the vehicle now matches to. * Starts at the previous match and then looks ahead from there to find good * spatial matches. Then determines which spatial match is best by looking * at temporal match. Updates the vehicleState with the resulting best * temporal match. * * @param vehicleState * the previous vehicle state */ public void matchNewFixForPredictableVehicle(VehicleState vehicleState) { // Make sure state is coherent if (!vehicleState.isPredictable() || vehicleState.getMatch() == null) { throw new RuntimeException("Called AvlProcessor.matchNewFix() " + "for a vehicle that was not already predictable. " + vehicleState); } logger.debug("Matching already predictable vehicle using new AVL " + "report. The old spatial match is {}", vehicleState); // Find possible spatial matches List<SpatialMatch> spatialMatches = SpatialMatcher .getSpatialMatches(vehicleState); logger.debug("For vehicleId={} found the following {} spatial " + "matches: {}", vehicleState.getVehicleId(), spatialMatches.size(), spatialMatches); // Find best temporal match of the spatial matches TemporalMatch bestTemporalMatch = TemporalMatcher.getInstance() .getBestTemporalMatch(vehicleState, spatialMatches); // Log this as info since matching is a significant milestone logger.info("For vehicleId={} the best match is {}", vehicleState.getVehicleId(), bestTemporalMatch); // If didn't get a match then remember such in VehicleState if (bestTemporalMatch == null) vehicleState.incrementNumberOfBadMatches(); // If vehicle not making progress then return boolean notMakingProgress = handleIfVehicleNotMakingProgress( bestTemporalMatch, vehicleState); if (notMakingProgress) return; // Record this match unless the match was null and haven't // reached number of bad matches. if (bestTemporalMatch != null || vehicleState.overLimitOfBadMatches()) { // If not over the limit of bad matches then handle normally if (bestTemporalMatch != null || !vehicleState.overLimitOfBadMatches()) { // Set the match of the vehicle. vehicleState.setMatch(bestTemporalMatch); } else { // Exceeded allowable number of bad matches so make vehicle // unpredictable due to bad matches log that info. // Log that vehicle is being made unpredictable as a // VehicleEvent String eventDescription = "Vehicle had " + vehicleState.numberOfBadMatches() + " bad spatial matches in a row" + " and so was made unpredictable."; logger.warn("For vehicleId={} {}", vehicleState.getVehicleId(), eventDescription); // Remove the predictions for the vehicle makeVehicleUnpredictable(vehicleState.getVehicleId(), eventDescription, VehicleEvent.NO_MATCH); // Remove block assignment from vehicle vehicleState.unsetBlock(BlockAssignmentMethod.COULD_NOT_MATCH); } } else { logger.info("For vehicleId={} got a bad match, {} in a row, so " + "not updating match for vehicle", vehicleState.getVehicleId(), vehicleState.numberOfBadMatches()); } // If schedule adherence is bad then try matching vehicle to assignment // again. This can make vehicle unpredictable if can't match vehicle to // assignment. if (vehicleState.isPredictable() && vehicleState.lastMatchIsValid()) verifyRealTimeSchAdh(vehicleState); } /** * When matching a vehicle to a route we are currently assuming that we * cannot make predictions or match a vehicle to a specific trip until after * vehicle has started on its trip. This is because there will be multiple * trips per route and we cannot tell which one the vehicle is on time wise * until the vehicle has started the trip. * * @param match * @return True if the match can be used when matching vehicle to a route */ private static boolean matchOkForRouteMatching(SpatialMatch match) { return match.awayFromTerminals(getTerminalDistanceForRouteMatching()); } /** * When assigning a vehicle to a block then this method should be called to * update the VehicleState and log a corresponding VehicleEvent. If block * assignments are to be exclusive then any old vehicle on that assignment * will be have its assignment removed. * * @param bestMatch * The TemporalMatch that the vehicle was matched to. If set then * vehicle will be made predictable and if block assignments are * to be exclusive then any old vehicle on that assignment will * be have its assignment removed. If null then vehicle will be * configured to be not predictable. * @param vehicleState * The VehicleState for the vehicle to be updated * @param possibleBlockAssignmentMethod * The type of assignment, such as * BlockAssignmentMethod.AVL_FEED_ROUTE_ASSIGNMENT or * BlockAssignmentMethod.AVL_FEED_BLOCK_ASSIGNMENT * @param assignmentId * The ID of the route or block that getting assigned to * @param assignmentType * A string for logging and such indicating whether assignment * made to a route or to a block. Should therefore be "block" or * "route". */ private void updateVehicleStateFromAssignment(TemporalMatch bestMatch, VehicleState vehicleState, BlockAssignmentMethod possibleBlockAssignmentMethod, String assignmentId, String assignmentType) { // Convenience variables AvlReport avlReport = vehicleState.getAvlReport(); String vehicleId = avlReport.getVehicleId(); // Make sure no other vehicle is using that assignment // if it is supposed to be exclusive. This needs to be done before // the VehicleDataCache is updated with info from the current // vehicle since this will affect all vehicles assigned to the // block. if (bestMatch != null) { unassignOtherVehiclesFromBlock(bestMatch.getBlock(), vehicleId); } // If got a valid match then keep track of state BlockAssignmentMethod blockAssignmentMethod = null; boolean predictable = false; Block block = null; if (bestMatch != null) { blockAssignmentMethod = possibleBlockAssignmentMethod; predictable = true; block = bestMatch.getBlock(); logger.info("vehicleId={} matched to {}Id={}. " + "Vehicle is now predictable. Match={}", vehicleId, assignmentType, assignmentId, bestMatch); // Record a corresponding VehicleEvent String eventDescription = "Vehicle successfully matched to " + assignmentType + " assignment and is now predictable."; VehicleEvent.create(avlReport, bestMatch, VehicleEvent.PREDICTABLE, eventDescription, true, // predictable false, // becameUnpredictable null); // supervisor } else { logger.debug("For vehicleId={} could not assign to {}Id={}. " + "Therefore vehicle is not being made predictable.", vehicleId, assignmentType, assignmentId); } // Update the vehicle state with the determined block assignment // and match. Of course might not have been successful in // matching vehicle, but still should update VehicleState. vehicleState.setMatch(bestMatch); vehicleState.setBlock(block, blockAssignmentMethod, assignmentId, predictable); } /** * Attempts to match vehicle to the specified route by finding appropriate * block assignment. Updates the VehicleState with the new block assignment * and match. These will be null if vehicle could not successfully be * matched to route. * * @param routeId * @param vehicleState * @return True if successfully matched vehicle to block assignment for * specified route */ private boolean matchVehicleToRouteAssignment(String routeId, VehicleState vehicleState) { // Make sure params are good if (routeId == null) { logger.error("matchVehicleToRouteAssignment() called with null " + "routeId. {}", vehicleState); } logger.debug("Matching unassigned vehicle to routeId={}. {}", routeId, vehicleState); // Convenience variables AvlReport avlReport = vehicleState.getAvlReport(); // Determine which blocks are currently active for the route. // Multiple services can be active on a given day. Therefore need // to look at all the active ones to find out what blocks are active... List<Block> allBlocksForRoute = new ArrayList<Block>(); ServiceUtils serviceUtils = Core.getInstance().getServiceUtils(); Collection<String> serviceIds = serviceUtils.getServiceIds(avlReport.getDate()); for (String serviceId : serviceIds) { List<Block> blocksForService = Core.getInstance().getDbConfig() .getBlocksForRoute(serviceId, routeId); if (blocksForService != null) { allBlocksForRoute.addAll(blocksForService); } } List<SpatialMatch> allPotentialSpatialMatchesForRoute = new ArrayList<SpatialMatch>(); // Go through each block and determine best spatial matches for (Block block : allBlocksForRoute) { // If the block isn't active at this time then ignore it. This way // don't look at each trip to see if it is active which is important // because looking at each trip means all the trip data including // travel times needs to be lazy loaded, which can be slow. if (!block.isActive(avlReport.getDate())) { if (logger.isDebugEnabled()) { logger.debug("For vehicleId={} ignoring block ID {} with " + "start_time={} and end_time={} because not " + "active for time {}", avlReport.getVehicleId(), block.getId(), Time.timeOfDayStr(block.getStartTime()), Time.timeOfDayStr(block.getEndTime()), Time.timeStr(avlReport.getDate())); } continue; } // Determine which trips for the block are active. If none then // continue to the next block List<Trip> potentialTrips = block .getTripsCurrentlyActive(avlReport); if (potentialTrips.isEmpty()) continue; logger.debug("For vehicleId={} examining potential trips for " + "match to block ID {}. {}", avlReport.getVehicleId(), block.getId(), potentialTrips); // Get the potential spatial matches List<SpatialMatch> spatialMatchesForBlock = SpatialMatcher .getSpatialMatches(vehicleState.getAvlReport(), block, potentialTrips, MatchingType.AUTO_ASSIGNING_MATCHING); // Add appropriate spatial matches to list for (SpatialMatch spatialMatch : spatialMatchesForBlock) { if (!SpatialMatcher.problemMatchDueToLackOfHeadingInfo( spatialMatch, vehicleState, MatchingType.AUTO_ASSIGNING_MATCHING) && matchOkForRouteMatching(spatialMatch)) allPotentialSpatialMatchesForRoute.add(spatialMatch); } } // End of going through each block to determine spatial matches // For the spatial matches get the best temporal match TemporalMatch bestMatch = TemporalMatcher.getInstance() .getBestTemporalMatchComparedToSchedule(avlReport, allPotentialSpatialMatchesForRoute); logger.debug("For vehicleId={} best temporal match is {}", avlReport.getVehicleId(), bestMatch); // Update the state of the vehicle updateVehicleStateFromAssignment(bestMatch, vehicleState, BlockAssignmentMethod.AVL_FEED_ROUTE_ASSIGNMENT, routeId, "route"); // Return true if predictable return bestMatch != null; } /** * Attempts to match the vehicle to the new block assignment. Updates the * VehicleState with the new block assignment and match. These will be null * if vehicle could not successfully be matched to block. * * @param block * @param vehicleState * @return True if successfully matched vehicle to block assignment */ private boolean matchVehicleToBlockAssignment(Block block, VehicleState vehicleState) { // Make sure params are good if (block == null) { logger.error("matchVehicleToBlockAssignment() called with null " + "block. {}", vehicleState); } logger.debug("Matching unassigned vehicle to block assignment {}. {}", block.getId(), vehicleState); // Convenience variables AvlReport avlReport = vehicleState.getAvlReport(); // Determine best spatial matches for trips that are currently // active. Currently active means that the AVL time is within // reasonable range of the start time and within the end time of // the trip. Matching type is set to MatchingType.STANDARD_MATCHING, // which means the matching can be more lenient than with // MatchingType.AUTO_ASSIGNING_MATCHING, because the AVL feed is // specifying the block assignment so it should find a match even // if it pretty far off. List<Trip> potentialTrips = block.getTripsCurrentlyActive(avlReport); List<SpatialMatch> spatialMatches = SpatialMatcher.getSpatialMatches(vehicleState.getAvlReport(), block, potentialTrips, MatchingType.STANDARD_MATCHING); logger.debug("For vehicleId={} and blockId={} spatial matches={}", avlReport.getVehicleId(), block.getId(), spatialMatches); // Determine the best temporal match TemporalMatch bestMatch = TemporalMatcher.getInstance() .getBestTemporalMatchComparedToSchedule(avlReport, spatialMatches); logger.debug("Best temporal match for vehicleId={} is {}", avlReport.getVehicleId(), bestMatch); // If best match is a non-layover but cannot confirm that the heading // is acceptable then don't consider this a match. Instead, wait till // get another AVL report at a different location so can see if making // progress along route in proper direction. if (SpatialMatcher.problemMatchDueToLackOfHeadingInfo(bestMatch, vehicleState, MatchingType.STANDARD_MATCHING)) { logger.debug("Found match but could not confirm that heading is " + "proper. Therefore not matching vehicle to block. {}", bestMatch); return false; } // If couldn't find an adequate spatial/temporal match then resort // to matching to a layover stop at a terminal. if (bestMatch == null) { logger.debug("For vehicleId={} could not find reasonable " + "match so will try to match to layover stop.", avlReport.getVehicleId()); Trip trip = TemporalMatcher.getInstance() .matchToLayoverStopEvenIfOffRoute(avlReport, potentialTrips); if (trip != null) { // Determine distance to first stop of trip Location firstStopInTripLoc = trip.getStopPath(0).getStopLocation(); double distanceToSegment = firstStopInTripLoc.distance(avlReport.getLocation()); SpatialMatch beginningOfTrip = new SpatialMatch( avlReport.getTime(), block, block.getTripIndex(trip), 0, // stopPathIndex 0, // segmentIndex distanceToSegment, 0.0); // distanceAlongSegment bestMatch = new TemporalMatch(beginningOfTrip, new TemporalDifference(0)); logger.debug("For vehicleId={} could not find reasonable " + "match for blockId={} so had to match to layover. " + "The match is {}", avlReport.getVehicleId(), block.getId(), bestMatch); } else { logger.debug("For vehicleId={} couldn't find match for " + "blockId={}", avlReport.getVehicleId(), block.getId()); } } // Sometimes get a bad assignment where there is already a valid vehicle // with the assignment and the new match is actually far away from the // route, indicating driver might have entered wrong ID or never // logged out. For this situation ignore the match. if (bestMatch != null && matchProblematicDueOtherVehicleHavingAssignment(bestMatch, vehicleState)) { logger.error("Got a match for vehicleId={} but that assignment is " + "already taken by another vehicle and the new match " + "doesn't appear to be valid because it is far away from " + "the route. {} {}", avlReport.getVehicleId(), bestMatch, avlReport); return false; } // Update the state of the vehicle updateVehicleStateFromAssignment(bestMatch, vehicleState, BlockAssignmentMethod.AVL_FEED_BLOCK_ASSIGNMENT, block.getId(), "block"); // Return true if predictable return bestMatch != null; } /** * Determines if match is problematic since other vehicle already has * assignment and the other vehicle seems to be more appropriate. Match is * problematic if 1) exclusive matching is enabled, 2) other non-schedule * based vehicle already has the assignment, 3) the other vehicle that * already has the assignment isn't having any problems such as vehicle * being delayed, and 4) the new match is far away from the route which * implies that it might be a mistaken login. * <p> * Should be noted that this issue was encountered with sfmta on 1/1/2016 * around 15:00 for vehicle 8660 when avl feed showed it getting block * assignment 573 even though it was far from the route and vehicle 8151 * already had that assignment and actually was on the route. This * can happen if driver enters wrong assignment, or perhaps if they * never log out. * * @param match * @param vehicleState * @return true if the match is problematic and should not be used */ private boolean matchProblematicDueOtherVehicleHavingAssignment( TemporalMatch match, VehicleState vehicleState) { // If no match in first place then not a problem if (match == null) return false; // If matches don't need to be exclusive then don't have a problem Block block = match.getBlock(); if (!block.shouldBeExclusive()) return false; // If no other non-schedule based vehicle assigned to the block then // not a problem Collection<String> vehiclesAssignedToBlock = VehicleDataCache .getInstance().getVehiclesByBlockId(block.getId()); if (vehiclesAssignedToBlock.isEmpty()) // No other vehicle has assignment so not a problem return false; String otherVehicleId = null; for (String vehicleId : vehiclesAssignedToBlock) { otherVehicleId = vehicleId; VehicleState otherVehicleState = VehicleStateManager.getInstance() .getVehicleState(otherVehicleId); // If other vehicle that has assignment is schedule based then not // a problem to take its assignment away if (otherVehicleState.isForSchedBasedPreds()) return false; // If that other vehicle actually having any problem then not a // problem to take assignment away if (!otherVehicleState.isPredictable() || vehicleState.isDelayed()) return false; } // So far we know that another vehicle has exclusive assignment and // there are no problems with that vehicle. This means the new match // could be a mistake. Shouldn't use it if the new vehicle is far // away from route (it matches to a layover where matches are lenient), // indicating that the vehicle might have gotten wrong assignment while // doing something else. if (match.getDistanceToSegment() > maxDistanceForAssignmentGrab.getValue()) { // Match is far away from route so consider it to be invalid. // Log an error logger.error( "For agencyId={} got a match for vehicleId={} but that " + "assignment is already taken by vehicleId={} and the new " + "match doesn't appear to be valid because it is more " + "than {}m from the route. {} {}", AgencyConfig.getAgencyId(), vehicleState.getVehicleId(), otherVehicleId, maxDistanceForAssignmentGrab.getValue(), match, vehicleState.getAvlReport()); // Only send e-mail error rarely if (shouldSendMessage(vehicleState.getVehicleId(), vehicleState.getAvlReport())) { logger.error(Markers.email(), "For agencyId={} got a match for vehicleId={} but that " + "assignment is already taken by vehicleId={} and the new " + "match doesn't appear to be valid because it is more " + "than {}m from the route. {} {}", AgencyConfig.getAgencyId(), vehicleState.getVehicleId(), otherVehicleId, maxDistanceForAssignmentGrab.getValue(), match, vehicleState.getAvlReport()); } return true; } else { // The new match is reasonably close to the route so should consider // it valid return false; } } // Keyed on vehicleId. Contains last time problem grabbing assignment // message sent for the vehicle. For reducing number of emails sent // when there is a problem. private Map<String, Long> problemGrabbingAssignmentMap = new HashMap<String, Long>(); /** * For reducing e-mail logging messages when problem grabbing assignment. * Java property transitime.avl.emailMessagesWhenAssignmentGrabImproper must * be true for e-mail to be sent when there is an error. * * @param vehicleId * @param avlReport * @return true if should send message */ private boolean shouldSendMessage(String vehicleId, AvlReport avlReport) { Long lastTimeSentForVehicle = problemGrabbingAssignmentMap.get(vehicleId); // If message not yet sent for vehicle or it has been more than 10 minutes... if (emailMessagesWhenAssignmentGrabImproper.getValue() && (lastTimeSentForVehicle == null || avlReport.getTime() > lastTimeSentForVehicle + 30*Time.MS_PER_MIN)) { problemGrabbingAssignmentMap.put(vehicleId, avlReport.getTime()); return true; } else return false; } /** * If the block assignment is supposed to be exclusive then looks for any * vehicles assigned to the specified block and removes the assignment from * them. This of course needs to be called before a vehicle is assigned to a * block since *ALL* vehicles assigned to the block will have their * assignment removed. * * @param block * @param newVehicleId * for logging message */ private void unassignOtherVehiclesFromBlock(Block block, String newVehicleId) { // Determine vehicles assigned to block Collection<String> vehiclesAssignedToBlock = VehicleDataCache .getInstance().getVehiclesByBlockId(block.getId()); // For each vehicle assigned to the block unassign it VehicleStateManager stateManager = VehicleStateManager.getInstance(); for (String vehicleId : vehiclesAssignedToBlock) { VehicleState vehicleState = stateManager.getVehicleState(vehicleId); if (block.shouldBeExclusive() || vehicleState.isForSchedBasedPreds()) { String description = "Assigning vehicleId=" + newVehicleId + " to blockId=" + block.getId() + " but " + "vehicleId=" + vehicleId + " already assigned to that block so " + "removing assignment from vehicleId=" + vehicleId + "."; logger.info(description); makeVehicleUnpredictableAndGrabAssignment(vehicleState, description, VehicleEvent.ASSIGNMENT_GRABBED); } } } /** * To be called when vehicle doesn't already have a block assignment or the * vehicle is being reassigned. Uses block assignment from the AvlReport to * try to match the vehicle to the assignment. If successful then the * vehicle can be made predictable. The AvlReport is obtained from the * vehicleState parameter. * * @param avlReport * @param vehicleState * provides current AvlReport plus is updated by this method with * the new state. * @return true if successfully assigned vehicle */ public boolean matchVehicleToAssignment(VehicleState vehicleState) { logger.debug("Matching unassigned vehicle to assignment. {}", vehicleState); // Initialize some variables AvlReport avlReport = vehicleState.getAvlReport(); // Remove old block assignment if there was one if (vehicleState.isPredictable() && vehicleState.hasNewAssignment(avlReport)) { String eventDescription = "For vehicleId=" + vehicleState.getVehicleId() + " the vehicle assignment is being " + "changed to assignmentId=" + vehicleState.getAssignmentId(); makeVehicleUnpredictableAndTerminateAssignment(vehicleState, eventDescription, VehicleEvent.ASSIGNMENT_CHANGED); } // If the vehicle has a block assignment from the AVLFeed // then use it. Block block = BlockAssigner.getInstance().getBlockAssignment(avlReport); if (block != null) { // There is a block assignment from AVL feed so use it. return matchVehicleToBlockAssignment(block, vehicleState); } else { // If there is a route assignment from AVL feed us it String routeId = BlockAssigner.getInstance().getRouteIdAssignment( avlReport); if (routeId != null) { // There is a route assignment so use it return matchVehicleToRouteAssignment(routeId, vehicleState); } } // This method called when there is an assignment from AVL feed. But // if that assignment is invalid then will make it here. Try the // auto assignment feature in case it is enabled. boolean autoAssigned = automaticalyMatchVehicleToAssignment(vehicleState); if (autoAssigned) return true; // There was no valid block or route assignment from AVL feed so can't // do anything. But set the block assignment for the vehicle // so it is up to date. This call also sets the vehicle state // to be unpredictable. BlockAssignmentMethod blockAssignmentMethod = null; vehicleState.unsetBlock(blockAssignmentMethod); return false; } /** * For when vehicle didn't get an assignment from the AVL feed and the * vehicle previously was predictable and was matched to an assignment then * see if can continue to use the old assignment. * * @param vehicleState */ private void handlePredictableVehicleWithoutAvlAssignment( VehicleState vehicleState) { String oldAssignment = vehicleState.getAssignmentId(); // Had a valid old assignment. If haven't had too many bad // assignments in a row then use the old assignment. if (vehicleState.getBadAssignmentsInARow() < allowableBadAssignments .getValue()) { logger.warn("AVL report did not include an assignment for " + "vehicleId={} but badAssignmentsInARow={} which " + "is less than allowableBadAssignments={} so using " + "the old assignment={}", vehicleState.getVehicleId(), vehicleState.getBadAssignmentsInARow(), allowableBadAssignments.getValue(), vehicleState.getAssignmentId()); // Create AVL report with the old assignment and then use it // to update the vehicle state AvlReport modifiedAvlReport = new AvlReport( vehicleState.getAvlReport(), oldAssignment, AssignmentType.PREVIOUS); vehicleState.setAvlReport(modifiedAvlReport); matchNewFixForPredictableVehicle(vehicleState); // Increment the bad assignments count vehicleState.setBadAssignmentsInARow(vehicleState .getBadAssignmentsInARow() + 1); } else { // Vehicle was predictable but now have encountered too many // problem assignments. Therefore make vehicle unpredictable. String eventDescription = "VehicleId=" + vehicleState.getVehicleId() + " was assigned to blockId=" + oldAssignment + " but received " + vehicleState.getBadAssignmentsInARow() + " null assignments in a row, which is configured by " + "transitime.core.allowableBadAssignments to be too many, " + "so making vehicle unpredictable."; makeVehicleUnpredictable(vehicleState.getVehicleId(), eventDescription, VehicleEvent.ASSIGNMENT_CHANGED); } } /** * For when vehicle is not predictable and didn't have previous assignment. * Since this method is to be called when vehicle isn't assigned and didn't * get a valid assignment through the feed should try to automatically * assign the vehicle based on how it matches to a currently unmatched * block. If it can match the vehicle then this method fully processes the * match, generating predictions and such. * * @param vehicleState * @return true if auto assigned vehicle */ private boolean automaticalyMatchVehicleToAssignment(VehicleState vehicleState) { // If actually creating a schedule based prediction if (vehicleState.isForSchedBasedPreds()) return false; if (!AutoBlockAssigner.enabled()) { logger.info("Could not automatically assign vehicleId={} because " + "AutoBlockAssigner not enabled.", vehicleState.getVehicleId()); return false; } logger.info("Trying to automatically assign vehicleId={}", vehicleState.getVehicleId()); // Try to match vehicle to a block assignment if that feature is enabled AutoBlockAssigner autoAssigner = new AutoBlockAssigner(vehicleState); TemporalMatch bestMatch = autoAssigner.autoAssignVehicleToBlockIfEnabled(); if (bestMatch != null) { // Successfully matched vehicle to block so make vehicle predictable logger.info("Auto matched vehicleId={} to a block assignment. {}", vehicleState.getVehicleId(), bestMatch); // Update the state of the vehicle updateVehicleStateFromAssignment(bestMatch, vehicleState, BlockAssignmentMethod.AUTO_ASSIGNER, bestMatch.getBlock() .getId(), "block"); return true; } return false; } /** * For when don't have valid assignment for vehicle. If have a valid old * assignment and haven't gotten too many bad assignments in a row then * simply use the old assignment. This is handy for when the assignment * portion of the AVL feed does not send assignment data for every report. * * @param vehicleState */ private void handleProblemAssignment(VehicleState vehicleState) { String oldAssignment = vehicleState.getAssignmentId(); boolean wasPredictable = vehicleState.isPredictable(); logger.info("No assignment info for vehicleId={} so trying to assign " + "vehicle without it.", vehicleState.getVehicleId()); // If the vehicle previously was predictable and had an assignment // then see if can continue to use the old assignment. if (wasPredictable && oldAssignment != null) { handlePredictableVehicleWithoutAvlAssignment(vehicleState); } else { // Vehicle wasn't predictable and didn't have previous assignment. // Since this method is to be called when vehicle isn't assigned // and didn't get an assignment through the feed should try to // automatically assign the vehicle based on how it matches to // a currently unmatched block. automaticalyMatchVehicleToAssignment(vehicleState); } } /** * Looks at the last match in vehicleState to determine if at end of block * assignment. Updates vehicleState if at end of block. Note that this will * not always work since might not actually get an AVL report that matches * to the last stop. * * @param vehicleState * @return True if end of the block was reached with the last match. */ private boolean handlePossibleEndOfBlock(VehicleState vehicleState) { // Determine if at end of block assignment TemporalMatch temporalMatch = vehicleState.getMatch(); if (temporalMatch != null) { VehicleAtStopInfo atStopInfo = temporalMatch.getAtStop(); if (atStopInfo != null && atStopInfo.atEndOfBlock()) { logger.info("For vehicleId={} the end of the block={} " + "was reached so will make vehicle unpredictable", vehicleState.getVehicleId(), temporalMatch.getBlock() .getId()); // At end of block assignment so remove it String eventDescription = "Block assignment " + vehicleState.getBlock().getId() + " ended for vehicle so it was made unpredictable."; makeVehicleUnpredictableAndTerminateAssignment(vehicleState, eventDescription, VehicleEvent.END_OF_BLOCK); // Return that end of block reached return true; } } // End of block wasn't reached so return false return false; } /** * If schedule adherence is not within bounds then will try to match the * vehicle to the assignment again. This can be important if system is run * for a while and then paused and then started up again. Vehicle might * continue to match to the pre-paused match, but by then the vehicle might * be on a whole different trip, causing schedule adherence to be really far * off. To prevent this the vehicle is re-matched to the assignment. * <p> * Updates vehicleState accordingly. * * @param vehicleState */ private void verifyRealTimeSchAdh(VehicleState vehicleState) { // If no schedule then there can't be real-time schedule adherence if (vehicleState.getBlock() == null || vehicleState.getBlock().isNoSchedule()) return; logger.debug("Confirming real-time schedule adherence for vehicleId={}", vehicleState.getVehicleId()); // Determine the schedule adherence for the vehicle TemporalDifference scheduleAdherence = RealTimeSchedAdhProcessor .generate(vehicleState); // If vehicle is just sitting at terminal past its scheduled departure // time then indicate such as an event. if (vehicleState.getMatch().isWaitStop() && scheduleAdherence != null && scheduleAdherence.isLaterThan(CoreConfig .getAllowableLateAtTerminalForLoggingEvent()) && vehicleState.getMatch().getAtStop() != null) { // Create description for VehicleEvent String stopId = vehicleState.getMatch().getStopPath().getStopId(); Stop stop = Core.getInstance().getDbConfig().getStop(stopId); Route route = vehicleState.getMatch().getRoute(); VehicleAtStopInfo stopInfo = vehicleState.getMatch().getAtStop(); Integer scheduledDepartureTime = stopInfo.getScheduleTime() .getDepartureTime(); String description = "Vehicle " + vehicleState.getVehicleId() + " still at stop " + stopId + " \"" + stop.getName() + "\" for route \"" + route.getName() + "\" " + scheduleAdherence.toString() + ". Scheduled departure time was " + Time.timeOfDayStr(scheduledDepartureTime); // Create, store in db, and log the VehicleEvent VehicleEvent.create(vehicleState.getAvlReport(), vehicleState.getMatch(), VehicleEvent.NOT_LEAVING_TERMINAL, description, true, // predictable false, // becameUnpredictable null); // supervisor } // Make sure the schedule adherence is reasonable if (scheduleAdherence != null && !scheduleAdherence.isWithinBounds()) { logger.warn( "For vehicleId={} schedule adherence {} is not " + "between the allowable bounds. Therefore trying to match " + "the vehicle to its assignmet again to see if get better " + "temporal match by matching to proper trip.", vehicleState.getVehicleId(), scheduleAdherence); // Log that vehicle is being made unpredictable as a VehicleEvent String eventDescription = "Vehicle had schedule adherence of " + scheduleAdherence + " which is beyond acceptable " + "limits. Therefore vehicle made unpredictable."; VehicleEvent.create(vehicleState.getAvlReport(), vehicleState.getMatch(), VehicleEvent.NO_MATCH, eventDescription, false, // predictable, true, // becameUnpredictable null); // supervisor // Clear out match because it is no good! This is especially // important for when determining arrivals/departures because // that looks at previous match and current match. vehicleState.setMatch(null); // Schedule adherence not reasonable so match vehicle to assignment // again. matchVehicleToAssignment(vehicleState); } } /** * Determines the real-time schedule adherence and stores the value in the * vehicleState. To be called after the vehicle is matched. * * @param vehicleState */ private void determineAndSetRealTimeSchAdh(VehicleState vehicleState) { // If no schedule then there can't be real-time schedule adherence if (vehicleState.getBlock() == null || vehicleState.getBlock().isNoSchedule()) return; logger.debug("Determining and setting real-time schedule adherence for " + "vehicleId={}", vehicleState.getVehicleId()); // Determine the schedule adherence for the vehicle TemporalDifference scheduleAdherence = RealTimeSchedAdhProcessor .generate(vehicleState); // Store the schedule adherence with the vehicle vehicleState.setRealTimeSchedAdh(scheduleAdherence); } /** * Processes the AVL report by matching to the assignment and generating * predictions and such. Sets VehicleState for the vehicle based on the * results. Also stores AVL report into the database (if not in playback * mode). * * @param avlReport * The new AVL report to be processed * @param recursiveCall * Set to true if this method is calling itself. Used to make * sure that any bug can't cause infinite recursion. */ private void lowLevelProcessAvlReport(AvlReport avlReport, boolean recursiveCall) { // Determine previous state of vehicle String vehicleId = avlReport.getVehicleId(); VehicleState vehicleState = VehicleStateManager.getInstance() .getVehicleState(vehicleId); // Since modifying the VehicleState should synchronize in case another // thread simultaneously processes data for the same vehicle. This // would be extremely rare but need to be safe. synchronized (vehicleState) { // Keep track of last AvlReport even if vehicle not predictable. vehicleState.setAvlReport(avlReport); // If part of consist and shouldn't be generating predictions // and such and shouldn't grab assignment the simply return // not that the last AVL report has been set for the vehicle. if (avlReport.ignoreBecauseInConsist()) { return; } // Do the matching depending on the old and the new assignment // for the vehicle. boolean matchAlreadyPredictableVehicle = vehicleState.isPredictable() && !vehicleState.hasNewAssignment(avlReport); boolean matchToNewAssignment = avlReport.hasValidAssignment() && (!vehicleState.isPredictable() || vehicleState .hasNewAssignment(avlReport)) && !vehicleState.previousAssignmentProblematic(avlReport); if (matchAlreadyPredictableVehicle) { // Vehicle was already assigned and assignment hasn't // changed so update the match of where the vehicle is // within the assignment. matchNewFixForPredictableVehicle(vehicleState); } else if (matchToNewAssignment) { // New assignment from AVL feed so match the vehicle to it matchVehicleToAssignment(vehicleState); } else { // Handle bad assignment where don't have assignment or such. // Will try auto assigning a vehicle if that feature is enabled. handleProblemAssignment(vehicleState); } // If the last match is actually valid then generate associated // data like predictions and arrival/departure times. if (vehicleState.isPredictable() && vehicleState.lastMatchIsValid()) { // Reset the counter vehicleState.setBadAssignmentsInARow(0); // If vehicle is delayed as indicated by not making forward // progress then store that in the vehicle state handlePossibleVehicleDelay(vehicleState); // Determine and store the schedule adherence. determineAndSetRealTimeSchAdh(vehicleState); // Only continue processing if vehicle is still predictable // since calling checkScheduleAdherence() can make it // unpredictable if schedule adherence is really bad. if (vehicleState.isPredictable()) { // Generates the corresponding data for the vehicle such as // predictions and arrival times MatchProcessor.getInstance().generateResultsOfMatch( vehicleState); // If finished block assignment then should remove // assignment boolean endOfBlockReached = handlePossibleEndOfBlock(vehicleState); // If just reached the end of the block and took the block // assignment away and made the vehicle unpredictable then // should see if the AVL report could be used to assign // vehicle to the next assignment. This is needed for // agencies like Zhengzhou which is frequency based and // where each block assignment is only a single trip and // when vehicle finishes one trip/block it can go into the // next block right away. if (endOfBlockReached) { if (recursiveCall) { // This method was already called recursively which // means unassigned vehicle at end of block but then // it got assigned to end of block again. This // indicates a bug since vehicles at end of block // shouldn't be reassigned to the end of the block // again. Therefore log problem and don't try to // assign vehicle again. logger.error( "AvlProcessor.lowLevelProcessAvlReport() " + "called recursively, which is wrong. {}", vehicleState); } else { // Actually process AVL report again to see if can // assign to new assignment. lowLevelProcessAvlReport(avlReport, true); } } // End of if end of block reached } } // If called recursively (because end of block reached) but // didn't match to new assignment then don't want to store the // vehicle state since already did that. if (recursiveCall && !vehicleState.isPredictable()) return; // Now that VehicleState has been updated need to update the // VehicleDataCache so that when data queried for API the proper // info is provided. VehicleDataCache.getInstance().updateVehicle(vehicleState); // Write out current vehicle state to db so can join it with AVL // data from db and get historical context of AVL report. org.transitime.db.structs.VehicleState dbVehicleState = new org.transitime.db.structs.VehicleState(vehicleState); Core.getInstance().getDbLogger().add(dbVehicleState); } // End of synchronizing on vehicleState } } /** * Returns the GPS time of the last regular (non-schedule based) GPS report * processed. Since AvlClient filters out reports that are for a previous * time for a vehicle even if the AVL feed continues to feed old data that * data will be ignored. In other words, the last AVL time will be for that * last valid AVL report. * * @return The GPS time in msec epoch time of last AVL report, or 0 if no * last AVL report */ public long lastAvlReportTime() { if (lastRegularReportProcessed == null) return 0; return lastRegularReportProcessed.getTime(); } /** * For storing the last regular (non-schedule based) AvlReport so can * determine if the AVL feed is working. Makes sure that report is newer * than the previous last regular report so that ignore possibly old data * that might come in from the AVL feed. * * @param avlReport * The new report to possibly store */ private void setLastAvlReport(AvlReport avlReport) { // Ignore schedule based predictions AVL reports since those are faked // and don't represent what is going on with the AVL feed if (avlReport.isForSchedBasedPreds()) return; // Only store report if it is a newer one. In this way we ignore // possibly old data that might come in from the AVL feed. if (lastRegularReportProcessed == null || avlReport.getTime() > lastRegularReportProcessed.getTime()) { lastRegularReportProcessed = avlReport; } } /** * Returns the last regular (non-schedule based) AvlReport. * * @return */ public AvlReport getLastAvlReport() { return lastRegularReportProcessed; } /** * Updates the VehicleState in the cache to have the new avlReport. Intended * for when want to update VehicleState AVL report but don't want to * actually process the report, such as for when get data too frequently and * only want to fully process some of it yet still use latest vehicle * location so that vehicles move on map really smoothly. * * @param avlReport */ public void cacheAvlReportWithoutProcessing(AvlReport avlReport) { VehicleState vehicleState = VehicleStateManager.getInstance().getVehicleState( avlReport.getVehicleId()); // Since modifying the VehicleState should synchronize in case another // thread simultaneously processes data for the same vehicle. This // would be extremely rare but need to be safe. synchronized (vehicleState) { // Update AVL report for cached VehicleState vehicleState.setAvlReport(avlReport); // Let vehicle data cache know that the vehicle state was updated // so that new IPC vehicle data will be created and cached and // made available to the API. VehicleDataCache.getInstance().updateVehicle(vehicleState); } } /** * First does housekeeping for the AvlReport (stores it in db, logs it, * etc). Processes the AVL report by matching to the assignment and * generating predictions and such. Sets VehicleState for the vehicle based * on the results. Also stores AVL report into the database (if not in * playback mode). * * @param avlReport * The new AVL report to be processed */ public void processAvlReport(AvlReport avlReport) { IntervalTimer timer = new IntervalTimer(); // Handle special case where want to not use assignment from AVL // report, most likely because want to test automatic assignment // capability if (AutoBlockAssigner.ignoreAvlAssignments() && !avlReport.isForSchedBasedPreds()) { logger.debug("Removing assignment from AVL report because " + "transitime.autoBlockAssigner.ignoreAvlAssignments=true. {}", avlReport); avlReport.setAssignment(null, AssignmentType.UNSET); } // The beginning of processing AVL data is an important milestone // in processing data so log it as info. logger.info("====================================================" + "AvlProcessor processing {}", avlReport); // Record when the AvlReport was actually processed. This is done here // so that the value will be set when the avlReport is stored in the // database using the DbLogger. avlReport.setTimeProcessed(); // Keep track of last AVL report processed so can determine if AVL // feed is up setLastAvlReport(avlReport); // Make sure that vehicle configuration is in cache and database VehicleDataCache.getInstance().cacheVehicleConfig(avlReport); // Store the AVL report into the database if (!CoreConfig.onlyNeedArrivalDepartures() && !avlReport.isForSchedBasedPreds()) Core.getInstance().getDbLogger().add(avlReport); // If any vehicles have timed out then handle them. This is done // here instead of using a regular timer so that it will work // even when in playback mode or when reading batch data. Core.getInstance().getTimeoutHandlerModule().storeAvlReport(avlReport); // Logging to syserr just for debugging. if (AvlConfig.shouldLogToStdOut()) { System.err.println("Processing avlReport for vehicleId=" + avlReport.getVehicleId() + // " AVL time=" + Time.timeStrMsec(avlReport.getTime()) + " " + avlReport + " ..."); } // Do the low level work of matching vehicle and then generating results lowLevelProcessAvlReport(avlReport, false); logger.debug("Processing AVL report took {}msec", timer); } }
gpl-3.0
ArlindNocaj/power-voronoi-diagram
src/kn/uni/voronoitreemap/extension/VoroCellObject.java
1140
/******************************************************************************* * Copyright (c) 2013 Arlind Nocaj, University of Konstanz. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * For distributors of proprietary software, other licensing is possible on request: arlind.nocaj@gmail.com * * This work is based on the publication below, please cite on usage, e.g., when publishing an article. * Arlind Nocaj, Ulrik Brandes, "Computing Voronoi Treemaps: Faster, Simpler, and Resolution-independent", Computer Graphics Forum, vol. 31, no. 3, June 2012, pp. 855-864 ******************************************************************************/ package kn.uni.voronoitreemap.extension; import kn.uni.voronoitreemap.j2d.PolygonSimple; /** * Provides callback method for notification. * @author Arlind Nocaj * */ public interface VoroCellObject { public void setVoroPolygon(PolygonSimple polygon); public void doFinalWork(); }
gpl-3.0
dested/CraftbukkitMaps
src/main/java/net/minecraft/server/ItemHoe.java
1827
package net.minecraft.server; // CraftBukkit start import org.bukkit.block.BlockState; import org.bukkit.craftbukkit.block.CraftBlockState; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.block.BlockPlaceEvent; // CraftBukkit end public class ItemHoe extends Item { public ItemHoe(int i, EnumToolMaterial enumtoolmaterial) { super(i); this.maxStackSize = 1; this.d(enumtoolmaterial.a()); } public boolean a(ItemStack itemstack, EntityHuman entityhuman, World world, int i, int j, int k, int l) { int i1 = world.getTypeId(i, j, k); int j1 = world.getTypeId(i, j + 1, k); if ((l == 0 || j1 != 0 || i1 != Block.GRASS.id) && i1 != Block.DIRT.id) { return false; } else { Block block = Block.SOIL; world.makeSound((double) ((float) i + 0.5F), (double) ((float) j + 0.5F), (double) ((float) k + 0.5F), block.stepSound.getName(), (block.stepSound.getVolume1() + 1.0F) / 2.0F, block.stepSound.getVolume2() * 0.8F); if (world.isStatic) { return true; } else { BlockState blockState = CraftBlockState.getBlockState(world, i, j, k); // CraftBukkit world.setTypeId(i, j, k, block.id); // CraftBukkit start - Hoes - blockface -1 for 'SELF' BlockPlaceEvent event = CraftEventFactory.callBlockPlaceEvent(world, entityhuman, blockState, i, j, k, block); if (event.isCancelled() || !event.canBuild()) { event.getBlockPlaced().setTypeId(blockState.getTypeId()); return false; } // CraftBukkit end itemstack.damage(1, entityhuman); return true; } } } }
gpl-3.0
ckpp/heart-diag-app
src/HeartDiagApp/build/preprocessed/heartdiagapp/core/io/SignalParser.java
161
package heartdiagapp.core.io; import heartdiagapp.core.dsp.Signal; import java.util.Vector; public interface SignalParser { Signal parse(Vector lines); }
gpl-3.0
bgyuri76/foto-test
stackmob-java-client-sdk-master/src/main/java/com/stackmob/sdk/net/HttpVerbWithPayload.java
695
/** * Copyright 2011 StackMob * * 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.stackmob.sdk.net; public enum HttpVerbWithPayload implements HttpVerb { POST, PUT }
gpl-3.0
odoepner/tippotle
tippotle-impl/src/main/java/org/oldo/ui/text/StyleAttributes.java
907
package org.oldo.ui.text; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import java.awt.Color; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static javax.swing.text.StyleConstants.setForeground; /** * Cached style attribute sets */ public final class StyleAttributes { private static final ConcurrentMap<Color, AttributeSet> cache = new ConcurrentHashMap<>(); public static AttributeSet forColor(Color color) { final AttributeSet attributeSet = cache.get(color); if (attributeSet != null) { return attributeSet; } else { final MutableAttributeSet attribs = new SimpleAttributeSet(); setForeground(attribs, color); cache.put(color, attribs); return attribs; } } }
gpl-3.0
ckaestne/CIDE
CIDE_Samples/cide_samples/Prevayler/org/prevayler/foundation/ObjectInputStreamWithClassLoader.java
935
//Prevayler(TM) - The Free-Software Prevalence Layer. //Copyright (C) 2001-2003 Klaus Wuestefeld //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. //Contributions: Aleksey Aristov. package org.prevayler.foundation; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; public class ObjectInputStreamWithClassLoader extends ObjectInputStream { ClassLoader _loader; public ObjectInputStreamWithClassLoader(InputStream stream, ClassLoader loader) throws IOException { super(stream); _loader = loader; } protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { return(_loader != null ? _loader.loadClass(v.getName()) : super.resolveClass(v)); } }
gpl-3.0
wtud/tsap
tsap-UItests/src/org/tribler/tsap/UItests/ThumbGridLandscapeUiTest.java
625
package org.tribler.tsap.UItests; import android.os.RemoteException; import com.android.uiautomator.core.UiObjectNotFoundException; /** * UI test cases for the thumbgrid fragment in landscape mode * * @author Niels Spruit */ public class ThumbGridLandscapeUiTest extends ThumbGridUiTest { /** * Launches the Tribler Play app on the device and sets the orientation to * Right * * @throws UiObjectNotFoundException * @throws RemoteException */ @Override protected void startTSAP() throws UiObjectNotFoundException, RemoteException { super.startTSAP(); getUiDevice().setOrientationRight(); } }
gpl-3.0
CDS-INSPIRE/InSpider
validation/src/main/java/nl/ipo/cds/validation/logical/OrExpression.java
1031
package nl.ipo.cds.validation.logical; import java.util.List; import nl.ipo.cds.validation.Expression; import nl.ipo.cds.validation.ValidationMessage; import nl.ipo.cds.validation.ValidatorContext; public class OrExpression<K extends Enum<K> & ValidationMessage<K, C>, C extends ValidatorContext<K, C>> extends AbstractLogicalNAryExpr<K, C> { public OrExpression (final List<Expression<K, C, Boolean>> inputs) { super (inputs); } @Override public boolean evaluate (final List<Boolean> inputValues) { for (final Boolean value: inputValues) { if (value != null && value) { return true; } } return false; } @Override public String toString () { final StringBuilder builder = new StringBuilder (); builder.append ('('); for (final Expression<K, C, Boolean> input: inputs) { if (builder.length () > 1) { builder.append (" or "); } builder.append (input.toString ()); } builder.append (')'); return builder.toString (); } }
gpl-3.0
bresalio/open-keychain
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DisplayTextActivity.java
3374
/* * Copyright (C) 2012-2015 Dominik Schürmann <dominik@dominikschuermann.de> * Copyright (C) 2010-2014 Thialfihar <thi@thialfihar.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.ui; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.Toast; import org.openintents.openpgp.OpenPgpMetadata; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult; import org.sufficientlysecure.keychain.ui.base.BaseActivity; import org.sufficientlysecure.keychain.util.FileHelper; public class DisplayTextActivity extends BaseActivity { public static final String EXTRA_RESULT = "result"; public static final String EXTRA_METADATA = "metadata"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setFullScreenDialogClose(Activity.RESULT_CANCELED, false); // Handle intent actions handleActions(savedInstanceState, getIntent()); } @Override protected void initLayout() { setContentView(R.layout.decrypt_text_activity); } /** * Handles all actions with this intent */ private void handleActions(Bundle savedInstanceState, Intent intent) { if (savedInstanceState != null) { return; } DecryptVerifyResult result = intent.getParcelableExtra(EXTRA_RESULT); OpenPgpMetadata metadata = intent.getParcelableExtra(EXTRA_METADATA); String plaintext; try { plaintext = FileHelper.readTextFromUri(this, intent.getData(), metadata.getCharset()); } catch (IOException e) { Toast.makeText(this, R.string.error_preparing_data, Toast.LENGTH_LONG).show(); return; } if (plaintext != null) { loadFragment(plaintext, result); } else { Toast.makeText(this, R.string.error_invalid_data, Toast.LENGTH_LONG).show(); finish(); } } private void loadFragment(String plaintext, DecryptVerifyResult result) { // Create an instance of the fragment Fragment frag = DisplayTextFragment.newInstance(plaintext, result); // Add the fragment to the 'fragment_container' FrameLayout // NOTE: We use commitAllowingStateLoss() to prevent weird crashes! getSupportFragmentManager().beginTransaction() .replace(R.id.decrypt_text_fragment_container, frag) .commitAllowingStateLoss(); // do it immediately! getSupportFragmentManager().executePendingTransactions(); } }
gpl-3.0
BjerknesClimateDataCentre/QuinCe
WebApp/src/uk/ac/exeter/QuinCe/jobs/UnrecognisedStatusException.java
514
package uk.ac.exeter.QuinCe.jobs; /** * Exception raised for an unrecognised job status * * @author Steve Jones * */ public class UnrecognisedStatusException extends Exception { /** * The serial version UID */ private static final long serialVersionUID = -5124308472992974683L; /** * Basic constructor * * @param status * The unrecognised status */ public UnrecognisedStatusException(String status) { super("The status '" + status + "' is not recognised"); } }
gpl-3.0
ImagoTrigger/sdrtrunk
src/main/java/io/github/dsheirer/audio/convert/thumbdv/message/request/InitializeCodecRequest.java
1739
/* * * * ****************************************************************************** * * Copyright (C) 2014-2019 Dennis Sheirer * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * ***************************************************************************** * * */ package io.github.dsheirer.audio.convert.thumbdv.message.request; import io.github.dsheirer.audio.convert.thumbdv.message.InitializeOption; import io.github.dsheirer.audio.convert.thumbdv.message.PacketField; /** * Initialize CODEC request packet */ public class InitializeCodecRequest extends AmbeRequest { private static final int INITIALIZE_OPTION_INDEX = 5; private InitializeOption mInitializeOption; public InitializeCodecRequest(InitializeOption option) { mInitializeOption = option; } @Override public PacketField getType() { return PacketField.PKT_INIT; } @Override public byte[] getData() { byte[] data = createMessage(2, getType()); data[INITIALIZE_OPTION_INDEX] = mInitializeOption.getCode(); return data; } }
gpl-3.0
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/org/bukkit/Bukkit.java
17720
package org.bukkit; import java.awt.image.BufferedImage; import java.io.File; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.bukkit.Warning.WarningState; import org.bukkit.command.CommandException; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.help.HelpMap; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.Recipe; import org.bukkit.map.MapView; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.ServicesManager; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scoreboard.ScoreboardManager; import org.bukkit.util.CachedServerIcon; import com.avaje.ebean.config.ServerConfig; /** * Represents the Bukkit core, for version and Server singleton handling */ public final class Bukkit { private static Server server; /** * Static class cannot be initialized. */ private Bukkit() {} /** * Gets the current {@link Server} singleton * * @return Server instance being ran */ public static Server getServer() { return server; } /** * Attempts to set the {@link Server} singleton. * <p> * This cannot be done if the Server is already set. * * @param server Server instance */ public static void setServer(Server server) { if (Bukkit.server != null) { throw new UnsupportedOperationException("Cannot redefine singleton Server"); } Bukkit.server = server; server.getLogger().info("This server is running " + getName() + " version " + getVersion() + " (Implementing API version " + getBukkitVersion() + ")"); } /** * @see Server#getName() */ public static String getName() { return server.getName(); } /** * @see Server#getVersion() */ public static String getVersion() { return server.getVersion(); } /** * @see Server#getBukkitVersion() */ public static String getBukkitVersion() { return server.getBukkitVersion(); } /** * This method exists for legacy reasons to provide backwards * compatibility. It will not exist at runtime and should not be used * under any circumstances. * * @Deprecated * @see Server#_INVALID_getOnlinePlayers() */ @Deprecated public static Player[] _INVALID_getOnlinePlayers() { return server._INVALID_getOnlinePlayers(); } /** * @see Server#getOnlinePlayers() */ public static Collection<? extends Player> getOnlinePlayers() { return server.getOnlinePlayers(); } /** * @see Server#getMaxPlayers() */ public static int getMaxPlayers() { return server.getMaxPlayers(); } /** * @see Server#getPort() */ public static int getPort() { return server.getPort(); } /** * @see Server#getViewDistance() */ public static int getViewDistance() { return server.getViewDistance(); } /** * @see Server#getIp() */ public static String getIp() { return server.getIp(); } /** * @see Server#getServerName() */ public static String getServerName() { return server.getServerName(); } /** * @see Server#getServerId() */ public static String getServerId() { return server.getServerId(); } /** * @see Server#getWorldType() */ public static String getWorldType() { return server.getWorldType(); } /** * @see Server#getGenerateStructures() */ public static boolean getGenerateStructures() { return server.getGenerateStructures(); } /** * @see Server#getAllowNether() */ public static boolean getAllowNether() { return server.getAllowNether(); } /** * @see Server#hasWhitelist() */ public static boolean hasWhitelist() { return server.hasWhitelist(); } /** * @see Server#broadcastMessage(String message) */ public static int broadcastMessage(String message) { return server.broadcastMessage(message); } /** * @see Server#getUpdateFolder() */ public static String getUpdateFolder() { return server.getUpdateFolder(); } /** * @see Server#getPlayer(String name) */ @Deprecated public static Player getPlayer(String name) { return server.getPlayer(name); } /** * @see Server#matchPlayer(String name) */ @Deprecated public static List<Player> matchPlayer(String name) { return server.matchPlayer(name); } /** * @see Server#getPlayer(java.util.UUID) */ public static Player getPlayer(UUID id) { return server.getPlayer(id); } /** * @see Server#getPluginManager() */ public static PluginManager getPluginManager() { return server.getPluginManager(); } /** * @see Server#getScheduler() */ public static BukkitScheduler getScheduler() { return server.getScheduler(); } /** * @see Server#getServicesManager() */ public static ServicesManager getServicesManager() { return server.getServicesManager(); } /** * @see Server#getWorlds() */ public static List<World> getWorlds() { return server.getWorlds(); } /** * @see Server#createWorld(WorldCreator options) */ public static World createWorld(WorldCreator options) { return server.createWorld(options); } /** * @see Server#unloadWorld(String name, boolean save) */ public static boolean unloadWorld(String name, boolean save) { return server.unloadWorld(name, save); } /** * @see Server#unloadWorld(World world, boolean save) */ public static boolean unloadWorld(World world, boolean save) { return server.unloadWorld(world, save); } /** * @see Server#getWorld(String name) */ public static World getWorld(String name) { return server.getWorld(name); } /** * @see Server#getWorld(UUID uid) */ public static World getWorld(UUID uid) { return server.getWorld(uid); } /** * @see Server#getMap(short id) * @deprecated Magic value */ @Deprecated public static MapView getMap(short id) { return server.getMap(id); } /** * @see Server#createMap(World world) */ public static MapView createMap(World world) { return server.createMap(world); } /** * @see Server#reload() */ public static void reload() { server.reload(); org.spigotmc.CustomTimingsHandler.reload(); // Spigot } /** * @see Server#getLogger() */ public static Logger getLogger() { return server.getLogger(); } /** * @see Server#getPluginCommand(String name) */ public static PluginCommand getPluginCommand(String name) { return server.getPluginCommand(name); } /** * @see Server#savePlayers() */ public static void savePlayers() { server.savePlayers(); } /** * @see Server#dispatchCommand(CommandSender sender, String commandLine) */ public static boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException { return server.dispatchCommand(sender, commandLine); } /** * @see Server#configureDbConfig(ServerConfig config) */ public static void configureDbConfig(ServerConfig config) { server.configureDbConfig(config); } /** * @see Server#addRecipe(Recipe recipe) */ public static boolean addRecipe(Recipe recipe) { return server.addRecipe(recipe); } /** * @see Server#getRecipesFor(ItemStack result) */ public static List<Recipe> getRecipesFor(ItemStack result) { return server.getRecipesFor(result); } /** * @see Server#recipeIterator() */ public static Iterator<Recipe> recipeIterator() { return server.recipeIterator(); } /** * @see Server#clearRecipes() */ public static void clearRecipes() { server.clearRecipes(); } /** * @see Server#resetRecipes() */ public static void resetRecipes() { server.resetRecipes(); } /** * @see Server#getCommandAliases() */ public static Map<String, String[]> getCommandAliases() { return server.getCommandAliases(); } /** * @see Server#getSpawnRadius() */ public static int getSpawnRadius() { return server.getSpawnRadius(); } /** * @see Server#setSpawnRadius(int value) */ public static void setSpawnRadius(int value) { server.setSpawnRadius(value); } /** * @see Server#getOnlineMode() */ public static boolean getOnlineMode() { return server.getOnlineMode(); } /** * @see Server#getAllowFlight() */ public static boolean getAllowFlight() { return server.getAllowFlight(); } /** * @see Server#isHardcore() */ public static boolean isHardcore() { return server.isHardcore(); } /** * @see Server#shutdown() */ public static void shutdown() { server.shutdown(); } /** * @see Server#broadcast(String message, String permission) */ public static int broadcast(String message, String permission) { return server.broadcast(message, permission); } /** * @see Server#getOfflinePlayer(String name) */ @Deprecated public static OfflinePlayer getOfflinePlayer(String name) { return server.getOfflinePlayer(name); } /** * @see Server#getOfflinePlayer(java.util.UUID) */ public static OfflinePlayer getOfflinePlayer(UUID id) { return server.getOfflinePlayer(id); } /** * @see Server#getPlayerExact(String name) */ @Deprecated public static Player getPlayerExact(String name) { return server.getPlayerExact(name); } /** * @see Server#getIPBans() */ public static Set<String> getIPBans() { return server.getIPBans(); } /** * @see Server#banIP(String address) */ public static void banIP(String address) { server.banIP(address); } /** * @see Server#unbanIP(String address) */ public static void unbanIP(String address) { server.unbanIP(address); } /** * @see Server#getBannedPlayers() */ public static Set<OfflinePlayer> getBannedPlayers() { return server.getBannedPlayers(); } /** * @see Server#getBanList(BanList.Type) */ public static BanList getBanList(BanList.Type type){ return server.getBanList(type); } /** * @see Server#setWhitelist(boolean value) */ public static void setWhitelist(boolean value) { server.setWhitelist(value); } /** * @see Server#getWhitelistedPlayers() */ public static Set<OfflinePlayer> getWhitelistedPlayers() { return server.getWhitelistedPlayers(); } /** * @see Server#reloadWhitelist() */ public static void reloadWhitelist() { server.reloadWhitelist(); } /** * @see Server#getConsoleSender() */ public static ConsoleCommandSender getConsoleSender() { return server.getConsoleSender(); } /** * @see Server#getOperators() */ public static Set<OfflinePlayer> getOperators() { return server.getOperators(); } /** * @see Server#getWorldContainer() */ public static File getWorldContainer() { return server.getWorldContainer(); } /** * @see Server#getMessenger() */ public static Messenger getMessenger() { return server.getMessenger(); } /** * @see Server#getAllowEnd() */ public static boolean getAllowEnd() { return server.getAllowEnd(); } /** * @see Server#getUpdateFolderFile() */ public static File getUpdateFolderFile() { return server.getUpdateFolderFile(); } /** * @see Server#getConnectionThrottle() */ public static long getConnectionThrottle() { return server.getConnectionThrottle(); } /** * @see Server#getTicksPerAnimalSpawns() */ public static int getTicksPerAnimalSpawns() { return server.getTicksPerAnimalSpawns(); } /** * @see Server#getTicksPerMonsterSpawns() */ public static int getTicksPerMonsterSpawns() { return server.getTicksPerMonsterSpawns(); } /** * @see Server#useExactLoginLocation() */ public static boolean useExactLoginLocation() { return server.useExactLoginLocation(); } /** * @see Server#getDefaultGameMode() */ public static GameMode getDefaultGameMode() { return server.getDefaultGameMode(); } /** * @see Server#setDefaultGameMode(GameMode mode) */ public static void setDefaultGameMode(GameMode mode) { server.setDefaultGameMode(mode); } /** * @see Server#getOfflinePlayers() */ public static OfflinePlayer[] getOfflinePlayers() { return server.getOfflinePlayers(); } /** * @see Server#createInventory(InventoryHolder owner, InventoryType type) */ public static Inventory createInventory(InventoryHolder owner, InventoryType type) { return server.createInventory(owner, type); } /** * @see Server#createInventory(InventoryHolder owner, InventoryType type, String title) */ public static Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { return server.createInventory(owner, type, title); } /** * @see Server#createInventory(InventoryHolder owner, int size) */ public static Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { return server.createInventory(owner, size); } /** * @see Server#createInventory(InventoryHolder owner, int size, String * title) */ public static Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { return server.createInventory(owner, size, title); } /** * @see Server#getHelpMap() */ public static HelpMap getHelpMap() { return server.getHelpMap(); } /** * @see Server#getMonsterSpawnLimit() */ public static int getMonsterSpawnLimit() { return server.getMonsterSpawnLimit(); } /** * @see Server#getAnimalSpawnLimit() */ public static int getAnimalSpawnLimit() { return server.getAnimalSpawnLimit(); } /** * @see Server#getWaterAnimalSpawnLimit() */ public static int getWaterAnimalSpawnLimit() { return server.getWaterAnimalSpawnLimit(); } /** * @see Server#getAmbientSpawnLimit() */ public static int getAmbientSpawnLimit() { return server.getAmbientSpawnLimit(); } /** * @see Server#isPrimaryThread() */ public static boolean isPrimaryThread() { return server.isPrimaryThread(); } /** * @see Server#getMotd() */ public static String getMotd() { return server.getMotd(); } /** * @see Server#getShutdownMessage() */ public static String getShutdownMessage() { return server.getShutdownMessage(); } /** * @see Server#getWarningState() */ public static WarningState getWarningState() { return server.getWarningState(); } /** * @see Server#getItemFactory() */ public static ItemFactory getItemFactory() { return server.getItemFactory(); } /** * @see Server#getScoreboardManager() */ public static ScoreboardManager getScoreboardManager() { return server.getScoreboardManager(); } /** * @see Server#getServerIcon() */ public static CachedServerIcon getServerIcon() { return server.getServerIcon(); } /** * @see Server#loadServerIcon(File) */ public static CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception { return server.loadServerIcon(file); } /** * @see Server#loadServerIcon(BufferedImage) */ public static CachedServerIcon loadServerIcon(BufferedImage image) throws IllegalArgumentException, Exception { return server.loadServerIcon(image); } /** * @see Server#setIdleTimeout(int) */ public static void setIdleTimeout(int threshold) { server.setIdleTimeout(threshold); } /** * @see Server#getIdleTimeout() */ public static int getIdleTimeout() { return server.getIdleTimeout(); } /** * @see Server#getUnsafe() */ @Deprecated public static UnsafeValues getUnsafe() { return server.getUnsafe(); } }
gpl-3.0
covers1624/ForestryLegacy
forestry_common/core/forestry/core/utils/Utils.java
6274
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.utils; import java.util.Arrays; import java.util.Iterator; import java.util.Random; import forestry.core.config.Config; import forestry.core.proxy.Proxies; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryLargeChest; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import buildcraft.api.tools.IToolWrench; public class Utils { private static EntityPlayer modPlayer; public static EntityPlayer getForestryPlayer(World world, int x, int y, int z) { if(modPlayer == null) { modPlayer = new EntityPlayer(world) { @Override public void sendChatToPlayer(String message) { } @Override public boolean canCommandSenderUseCommand(int var1, String var2) { return false; } @Override public ChunkCoordinates getPlayerCoordinates() { return null; } }; modPlayer.username = Config.fakeUserLogin; modPlayer.posX = x; modPlayer.posY = y; modPlayer.posZ = z; Proxies.log.info("Created player '%s' for Forestry.", modPlayer.username); if(Config.fakeUserAutoop) { MinecraftServer.getServerConfigurationManager(MinecraftServer.getServer()).addOp(modPlayer.username); Proxies.log.info("Opped player '%s'.", modPlayer.username); } } return modPlayer; } private static Random rand; public static int getUID() { if(rand == null) rand = new Random(); return rand.nextInt(); } @SuppressWarnings("rawtypes") public static void broadcastMessage(World world, String message) { for (Iterator iterator = world.playerEntities.iterator(); iterator.hasNext();) { EntityPlayer entityplayer = (EntityPlayer) iterator.next(); entityplayer.addChatMessage(message); } } public static IInventory getChest(IInventory inventory) { if (!(inventory instanceof TileEntityChest)) return inventory; TileEntityChest chest = (TileEntityChest) inventory; Vect[] adjacent = new Vect[] { new Vect(chest.xCoord + 1, chest.yCoord, chest.zCoord), new Vect(chest.xCoord - 1, chest.yCoord, chest.zCoord), new Vect(chest.xCoord, chest.yCoord, chest.zCoord + 1), new Vect(chest.xCoord, chest.yCoord, chest.zCoord - 1) }; for (Vect pos : adjacent) { TileEntity otherchest = chest.worldObj.getBlockTileEntity(pos.x, pos.y, pos.z); if (otherchest instanceof TileEntityChest) return new InventoryLargeChest("", chest, (TileEntityChest) otherchest); } return inventory; } public static <T> T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } public static int[] concat(int[] first, int[] second) { int[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } public static short[] concat(short[] first, short[] second) { short[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } public static float[] concat(float[] first, float[] second) { float[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } public static boolean isWrench(ItemStack itemstack) { return itemstack != null && itemstack.getItem() instanceof IToolWrench; } public static EnumTankLevel rateTankLevel(int scaled) { if (scaled < 5) return EnumTankLevel.EMPTY; else if (scaled < 30) return EnumTankLevel.LOW; else if (scaled < 60) return EnumTankLevel.MEDIUM; else if (scaled < 90) return EnumTankLevel.HIGH; else return EnumTankLevel.MAXIMUM; } public static boolean isReplaceableBlock(World world, int x, int y, int z) { int blockid = world.getBlockId(x, y, z); return blockid == Block.vine.blockID || blockid == Block.tallGrass.blockID || blockid == Block.deadBush.blockID || blockid == Block.snow.blockID || (Block.blocksList[blockid] != null && Block.blocksList[blockid].isBlockReplaceable(world, x, y, z)); } public static boolean isUseableByPlayer(EntityPlayer player, TileEntity tile, World world, int x, int y, int z) { if (world.getBlockTileEntity(x, y, z) != tile) return false; return player.getDistanceSq(x + 0.5D, y + 0.5D, z + 0.5D) <= 64.0D; } public static Entity spawnEntity(World world, Class<? extends Entity> entityClass, double x, double y, double z) { if(!EntityList.classToStringMapping.containsKey(entityClass)) return null; Entity spawn = EntityList.createEntityByName((String)EntityList.classToStringMapping.get(entityClass), world); if (spawn != null && spawn instanceof EntityLiving) { EntityLiving living = (EntityLiving)spawn; spawn.setLocationAndAngles(x, y, z, MathHelper.wrapAngleTo180_float(world.rand.nextFloat() * 360.0f), 0.0f); living.rotationYawHead = living.rotationYaw; living.renderYawOffset = living.rotationYaw; living.initCreature(); world.spawnEntityInWorld(spawn); living.playLivingSound(); } return spawn; } }
gpl-3.0
jefalbino/jsmart-rest-archetype
src/main/resources/archetype-resources/src/main/java/rest/RestController.java
1576
package ${package}.rest; import ${package}.adapter.Adapter; import ${package}.service.SpringService; import com.jsmartframework.web.annotation.RequestPath; import com.jsmartframework.web.manager.WebContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Map; @Controller @RequestPath("/home/v1/*") public class RestController { @Autowired private SpringService springService; @ResponseBody @RequestMapping(value="/test", method = RequestMethod.POST) public void doPost() throws IOException, JAXBException { // You can map query parameters and adapter via SpringMVC annotation on // method parameters, and also we provide an alternative way of getting // the query parameters and payload convertion as following Adapter adapter = WebContext.getContentFromJson(Adapter.class); System.out.println("JSON converted into class: " + adapter); Map<String, String> queryParams = WebContext.getQueryParams(); System.out.println("Query parameters: " + queryParams); // Alternative way of writing a response as XML // WebContext.writeResponseAsXml(adapter); // Writing response as JSON WebContext.writeResponseAsJson(adapter); } }
gpl-3.0
seapub/SourceCode
Java/corejava9/v1ch04/PackageTest/com/horstmann/corejava/Employee.java
906
package com.horstmann.corejava; // the classes in this file are part of this package import java.util.*; // import statements come after the package statement /** * @version 1.10 1999-12-18 * @author Cay Horstmann */ public class Employee { private String name; private double salary; private Date hireDay; public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } }
gpl-3.0
nicomda/AI
Practica2/src/mouserun/game/Maze.java
5333
/** * MouseRun. A programming game to practice building intelligent things. * Copyright (C) 2013 Muhammad Mustaqim * * This file is part of MouseRun. * * MouseRun 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. * * MouseRun 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 MouseRun. If not, see <http://www.gnu.org/licenses/>. **/ package mouserun.game; import java.util.*; /** * Class Maze is the board which the Mouse implementations will navigate through to * find the Cheese. */ public class Maze { private int width; private int height; private Grid[][] grids; /** * Creates a new instance of the maze. The maze will automatically build * the layout given the width and the height of the maze. * @param width The width (the number of columns) of the Maze. * @param height The height (the number of rows) of the Maze. */ public Maze(int width, int height) { this.width = width; this.height = height; buildMaze(); } // Builds the structure of the maze and adding walls to each grid to // connect the grids to another. This will call the generateMaze method. private void buildMaze() { grids = new Grid[this.width][this.height]; ArrayList<Wall> walls = new ArrayList<Wall>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { grids[x][y] = new Grid(x, y); } } // assign walls. When assigning walls, the grids at all sides of the // maze needs to be careful not to be connecting to anything else. for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Grid currentGrid = getGrid(x, y); if (x < width - 1) { Grid rightGrid = getGrid(x + 1, y); Wall wall = new Wall(currentGrid, rightGrid); currentGrid.addWall(wall); rightGrid.addWall(wall); walls.add(wall); } if (y < height - 1) { Grid topGrid = getGrid(x, y + 1); Wall wall = new Wall(currentGrid, topGrid); currentGrid.addWall(wall); topGrid.addWall(wall); walls.add(wall); } } } generateMaze(); } // Generates the maze using the Depth First Search algorithm. However, the // DFS algorithm only produce one path from one grid to another grid. Walls // will be opened at random in attempt to produce multiple paths for some // scenarios. The number of randomly opened walls will be 3% of the remaining // closed walls. private void generateMaze() { ArrayList<Grid> unvisitedGrids = new ArrayList<Grid>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { unvisitedGrids.add(getGrid(x, y)); } } Stack<Grid> pathStack = new Stack<Grid>(); Random random = new Random(); Grid currentGrid = getGrid(random.nextInt(width), random.nextInt(height)); unvisitedGrids.remove(currentGrid); pathStack.push(currentGrid); while (pathStack.size() > 0) { currentGrid = pathStack.peek(); ArrayList<Wall> wallsWithUnvisitedGrid = new ArrayList<Wall>(); for (Wall wall : currentGrid.getWalls()) { Grid mGrid = wall.getNextGrid(currentGrid); if (unvisitedGrids.contains(mGrid)) { wallsWithUnvisitedGrid.add(wall); } } if (wallsWithUnvisitedGrid.size() > 0) { Wall selectedWall = wallsWithUnvisitedGrid.get(random.nextInt(wallsWithUnvisitedGrid.size())); selectedWall.setOpened(true); Grid nextGrid = selectedWall.getNextGrid(currentGrid); unvisitedGrids.remove(nextGrid); pathStack.push(nextGrid); } else { pathStack.pop(); } } ArrayList<Wall> closedWalls = new ArrayList<Wall>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Grid grid = getGrid(x, y); for (Wall wall : grid.getWalls()) { if (!wall.isOpened()) { closedWalls.add(wall); } } } } int closedWallsToOpen = (int)(GameConfig.RATIO_CLOSED_WALL_TO_OPEN * closedWalls.size()); for (int i = 0; i < closedWallsToOpen; i++) { closedWalls.get(random.nextInt(closedWalls.size())).setOpened(true); } } /** * Get the Grid in the maze given its row and column number. * @param x The column number of the grid * @param y The row number of the grid * @return The Grid in the maze. */ public Grid getGrid(int x, int y) { return grids[x][y]; } /** * Get the number of columns defined for this maze. * @return The number of columns (the width) */ public int getWidth() { return this.width; } /** * Get the number of rows defined for this maze. * @return The number of rows (the height) */ public int getHeight() { return this.height; } }
gpl-3.0
Team4334/robot-code
src/api/gordian/Class.java
1051
package api.gordian; /** * The basic representation of classes inside of Gordian. A class constructs * objects which can be used as separate entities inside of a program. * * @author Joel Gallant <joelgallant236@gmail.com> */ public interface Class extends Object { /** * Constructs a unique instance of this class using arguments. * * @param arguments the arguments used to construct the new instance * @return a unique instance made by the class */ public Object contruct(Arguments arguments); /** * Returns a list of the acceptable constructors available for usage. * * Construction with arguments that don't fit one of these signatures will * fail. * * @return ways to construct instances */ public Signature[] contructors(); /** * Returns whether the class is the same or a child of this one. * * @param object class to test * @return if {@code object} is this class, or a child of it */ public boolean equals(Object object); }
gpl-3.0
guci314/playorm
src/main/java/com/alvazan/orm/layer9z/spi/db/inmemory/Table.java
3363
package com.alvazan.orm.layer9z.spi.db.inmemory; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import com.alvazan.orm.api.z8spi.Row; import com.alvazan.orm.api.z8spi.action.Column; import com.alvazan.orm.api.z8spi.action.IndexColumn; import com.alvazan.orm.api.z8spi.conv.ByteArray; import com.alvazan.orm.layer9z.spi.db.inmemory.IndexedRow.OurKey; public class Table { private Map<ByteArray, Row> keyToRow = new HashMap<ByteArray, Row>(); private String columnFamilyName; private SortType columnSortType; static final Comparator<ByteArray> UTF_COMPARATOR = new Utf8Comparator(); static final Comparator<ByteArray> INTEGER_COMPARATOR = new IntegerComparator(); static final Comparator<ByteArray> DECIMAL_COMPARATOR = new DecimalComparator(); private static Comparator<OurKey> utfPrefixComparator = new PrefixComparator(UTF_COMPARATOR); private static Comparator<OurKey> integerPrefixComparator = new PrefixComparator(INTEGER_COMPARATOR); private static Comparator<OurKey> decimalPrefixComparator = new PrefixComparator(DECIMAL_COMPARATOR); public Table(String columnFamily, SortType sortType) { this.columnSortType = sortType; this.columnFamilyName = columnFamily; } public Row findOrCreateRow(byte[] key) { ByteArray array = new ByteArray(key); Row row = keyToRow.get(array); if(row == null) { row = createSortedMap(); row.setKey(key); keyToRow.put(new ByteArray(key), row); } return row; } private Row createSortedMap() { TreeMap<ByteArray, Column> tree; Row row; switch (columnSortType) { case BYTES: tree = new TreeMap<ByteArray, Column>(); row = new RowImpl(tree); break; case UTF8: tree = new TreeMap<ByteArray, Column>(UTF_COMPARATOR); row = new RowImpl(tree); break; case INTEGER: tree = new TreeMap<ByteArray, Column>(INTEGER_COMPARATOR); row = new RowImpl(tree); break; case DECIMAL: tree = new TreeMap<ByteArray, Column>(DECIMAL_COMPARATOR); row = new RowImpl(tree); break; case DECIMAL_PREFIX: TreeMap<OurKey, IndexColumn> map = new TreeMap<OurKey, IndexColumn>(decimalPrefixComparator); row = new IndexedRow(map); break; case INTEGER_PREFIX: TreeMap<OurKey, IndexColumn> map2 = new TreeMap<OurKey, IndexColumn>(integerPrefixComparator); row = new IndexedRow(map2); break; case UTF8_PREFIX: TreeMap<OurKey, IndexColumn> map3 = new TreeMap<OurKey, IndexColumn>(utfPrefixComparator); row = new IndexedRow(map3); break; default: throw new UnsupportedOperationException("not supported type="+columnSortType); } return row; } public void removeRow(byte[] rowKey) { ByteArray key = new ByteArray(rowKey); keyToRow.remove(key); } public Row getRow(byte[] rowKey) { ByteArray key = new ByteArray(rowKey); Row row = keyToRow.get(key); if (row instanceof RowImpl) { if (((RowImpl) row).isExpired()) { keyToRow.remove(key); return null; } } return row; } @Override public String toString() { String t = ""; t += "columnFamilyName="+columnFamilyName+" columnSortType="+columnSortType; for(Row r : keyToRow.values()) { ByteArray b = new ByteArray(r.getKey()); t += "\nrowkey="+b.asString()+" row="+r; } return t; } public Set<ByteArray> findAllKeys() { return keyToRow.keySet(); } }
mpl-2.0
servinglynk/hmis-lynk-open-source
hmis-base-serialize/src/main/java/com/servinglynk/hmis/warehouse/core/model/Role.java
911
package com.servinglynk.hmis.warehouse.core.model; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("role") public class Role extends ClientModel { private UUID id; private String roleName; private String roleDescription; @JsonProperty("parentRole") private Role parentRole; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDescription() { return roleDescription; } public void setRoleDescription(String roleDescription) { this.roleDescription = roleDescription; } public Role getParentRole() { return parentRole; } public void setParentRole(Role parentRole) { this.parentRole = parentRole; } }
mpl-2.0
tuchida/rhino
toolsrc/org/mozilla/javascript/tools/shell/SecurityProxy.java
680
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.tools.shell; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.SecurityController; public abstract class SecurityProxy extends SecurityController { protected abstract void callProcessFileSecure(Context cx, Scriptable scope, String filename); }
mpl-2.0
jrconlin/mc_backup
base/mozglue/NativeZip.java
2619
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.mozglue; import org.mozilla.gecko.annotation.JNITarget; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; public class NativeZip implements NativeReference { private static final int DEFLATE = 8; private static final int STORE = 0; private volatile long mObj; private InputStream mInput; public NativeZip(String path) { mObj = getZip(path); } public NativeZip(InputStream input) { if (!(input instanceof ByteBufferInputStream)) { throw new IllegalArgumentException("Got " + input.getClass() + ", but expected ByteBufferInputStream!"); } ByteBufferInputStream bbinput = (ByteBufferInputStream)input; mObj = getZipFromByteBuffer(bbinput.mBuf); mInput = input; } @Override public void finalize() { release(); } public void close() { release(); } @Override public void release() { if (mObj != 0) { _release(mObj); mObj = 0; } mInput = null; } @Override public boolean isReleased() { return (mObj == 0); } public InputStream getInputStream(String path) { if (isReleased()) { throw new IllegalStateException("Can't get path \"" + path + "\" because NativeZip is closed!"); } return _getInputStream(mObj, path); } private static native long getZip(String path); private static native long getZipFromByteBuffer(ByteBuffer buffer); private static native void _release(long obj); private native InputStream _getInputStream(long obj, String path); @JNITarget private InputStream createInputStream(ByteBuffer buffer, int compression) { if (compression != STORE && compression != DEFLATE) { throw new IllegalArgumentException("Unexpected compression: " + compression); } InputStream input = new ByteBufferInputStream(buffer, this); if (compression == DEFLATE) { Inflater inflater = new Inflater(true); input = new InflaterInputStream(input, inflater); } return input; } }
mpl-2.0
servinglynk/hmis-lynk-open-source
hmis-load-processor-v2017/src/main/java/com/servinglynk/hmis/warehouse/upload/service/ClientDedupWorker.java
1999
package com.servinglynk.hmis.warehouse.upload.service; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.servinglynk.hmis.warehouse.base.util.DedupHelper; import com.servinglynk.hmis.warehouse.dao.ParentDaoFactory; import com.servinglynk.hmis.warehouse.model.v2017.Client; @Component public class ClientDedupWorker implements IClientDedupWorker { final static Logger logger = Logger.getLogger(ClientDedupWorker.class); @Autowired Environment env; @Autowired private ParentDaoFactory factory; @Autowired private DedupHelper dedupHelper; @Transactional @Scheduled(initialDelay=20,fixedDelay=10000) public void processWorkerLine() { try { List<Client> clients = factory.getClientDao().getAllNullDedupIdClients(); if(CollectionUtils.isNotEmpty(clients)) { String dedupSessionKey = dedupHelper.getAuthenticationHeader();; for(Client client : clients) { FileAppender appender = new FileAppender(); appender.setName("client-dedup-2017"); appender.setFile("logs/client-dedup-2017.log"); appender.setImmediateFlush(true); appender.setAppend(true); appender.setLayout(new PatternLayout()); appender.activateOptions(); logger.addAppender(appender); /** Perform full refresh base on Project group */ factory.getClientDao().updateDedupClient(client,dedupSessionKey); logger.removeAppender(appender); } } logger.info("======== Client Dedup Id Populator processed ======"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
mpl-2.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/new_plotter/engine/jfreechart/renderer/FormattedStackedBarRenderer.java
2572
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.new_plotter.engine.jfreechart.renderer; import java.awt.Color; import java.awt.Paint; import java.awt.Shape; import org.jfree.chart.renderer.category.StackedBarRenderer; import com.rapidminer.gui.new_plotter.engine.jfreechart.RenderFormatDelegate; import com.rapidminer.gui.new_plotter.utility.DataStructureUtils; /** * @author Marius Helf */ public class FormattedStackedBarRenderer extends StackedBarRenderer implements FormattedRenderer { private static final long serialVersionUID = 1L; private RenderFormatDelegate formatDelegate = new RenderFormatDelegate(); public FormattedStackedBarRenderer() { super(); } public FormattedStackedBarRenderer(boolean renderAsPercentages) { super(renderAsPercentages); } @Override public RenderFormatDelegate getFormatDelegate() { return formatDelegate; } @Override public Paint getItemPaint(int seriesIdx, int valueIdx) { Paint paintFromDelegate = getFormatDelegate().getItemPaint(seriesIdx, valueIdx); if (paintFromDelegate == null) { return super.getItemPaint(seriesIdx, valueIdx); } else { return paintFromDelegate; } } @Override public Shape getItemShape(int seriesIdx, int valueIdx) { Shape shapeFromDelegate = getFormatDelegate().getItemShape(seriesIdx, valueIdx); if (shapeFromDelegate == null) { return super.getItemShape(seriesIdx, valueIdx); } else { return shapeFromDelegate; } } @Override public Paint getItemOutlinePaint(int seriesIdx, int valueIdx) { if (getFormatDelegate().isItemSelected(seriesIdx, valueIdx)) { return super.getItemOutlinePaint(seriesIdx, valueIdx); } else { return DataStructureUtils.setColorAlpha(Color.LIGHT_GRAY, 20); } } }
agpl-3.0
JanMarvin/rstudio
src/gwt/src/org/rstudio/core/client/widget/WizardProjectTemplatePage.java
2156
/* * WizardProjectTemplatePage.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import org.rstudio.studio.client.projects.model.NewProjectInput; import org.rstudio.studio.client.projects.model.ProjectTemplateDescription; import org.rstudio.studio.client.projects.model.ProjectTemplateOptions; import org.rstudio.studio.client.projects.model.ProjectTemplateWidget; import org.rstudio.studio.client.projects.ui.newproject.NewDirectoryPage; public class WizardProjectTemplatePage extends NewDirectoryPage { public WizardProjectTemplatePage(ProjectTemplateDescription description) { super(description.getTitle(), description.getSubTitle(), description.getPageCaption(), description.getIcon(), description.getIconLarge()); description_ = description; } public final ProjectTemplateDescription getProjectTemplateDescription() { return description_; } @Override protected void initialize(NewProjectInput input) { super.initialize(input); // hide checkboxes generated by superclass chkGitInit_.setVisible(false); chkRenvInit_.setVisible(false); // add template-generated widget ptw_ = new ProjectTemplateWidget(description_); addWidget(ptw_); } @Override protected ProjectTemplateOptions getProjectTemplateOptions() { return ProjectTemplateOptions.create( description_, ptw_.collectInput()); } private ProjectTemplateWidget ptw_; private final ProjectTemplateDescription description_; }
agpl-3.0
sih4sing5hong5/han3_ji7_tsoo1_kian3
src/main/java/cc/ccomponent_adjuster/package-info.java
131
/** * 漢字部件核心套件包,含有部件定義以及實用工具。 * * @author Ihc */ package cc.ccomponent_adjuster;
agpl-3.0
jotomo/AndroidAPS
omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/communication/message/response/StatusResponse.java
5063
package info.nightscout.androidaps.plugins.pump.omnipod.driver.communication.message.response; import org.joda.time.Duration; import java.io.ByteArrayOutputStream; import java.io.IOException; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.driver.communication.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.DeliveryStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.PodProgressStatus; public class StatusResponse extends MessageBlock implements StatusUpdatableResponse { private static final int MESSAGE_LENGTH = 10; private final DeliveryStatus deliveryStatus; private final PodProgressStatus podProgressStatus; private final Duration timeActive; private final Double reservoirLevel; private final int ticksDelivered; private final double insulinDelivered; private final double bolusNotDelivered; private final byte podMessageCounter; private final AlertSet unacknowledgedAlerts; public StatusResponse(byte[] encodedData) { if (encodedData.length < MESSAGE_LENGTH) { throw new IllegalArgumentException("Not enough data"); } this.encodedData = ByteUtil.substring(encodedData, 1, MESSAGE_LENGTH - 1); deliveryStatus = DeliveryStatus.fromByte((byte) (ByteUtil.convertUnsignedByteToInt(encodedData[1]) >>> 4)); podProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[1] & 0x0F)); int minutes = ((encodedData[7] & 0x7F) << 6) | ((encodedData[8] & 0xFC) >>> 2); timeActive = Duration.standardMinutes(minutes); int highInsulinBits = (encodedData[2] & 0xF) << 9; int middleInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[3]) << 1; int lowInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[4]) >>> 7; ticksDelivered = (highInsulinBits | middleInsulinBits | lowInsulinBits); insulinDelivered = OmnipodConstants.POD_PULSE_SIZE * ticksDelivered; podMessageCounter = (byte) ((encodedData[4] >>> 3) & 0xf); bolusNotDelivered = OmnipodConstants.POD_PULSE_SIZE * (((encodedData[4] & 0x03) << 8) | ByteUtil.convertUnsignedByteToInt(encodedData[5])); unacknowledgedAlerts = new AlertSet((byte) (((encodedData[6] & 0x7f) << 1) | (ByteUtil.convertUnsignedByteToInt(encodedData[7]) >>> 7))); double reservoirValue = (((encodedData[8] & 0x3) << 8) + ByteUtil.convertUnsignedByteToInt(encodedData[9])) * OmnipodConstants.POD_PULSE_SIZE; if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) { reservoirLevel = null; } else { reservoirLevel = reservoirValue; } } @Override public MessageBlockType getType() { return MessageBlockType.STATUS_RESPONSE; } @Override public DeliveryStatus getDeliveryStatus() { return deliveryStatus; } @Override public PodProgressStatus getPodProgressStatus() { return podProgressStatus; } @Override public Duration getTimeActive() { return timeActive; } @Override public Double getReservoirLevel() { return reservoirLevel; } @Override public int getTicksDelivered() { return ticksDelivered; } @Override public double getInsulinDelivered() { return insulinDelivered; } @Override public double getBolusNotDelivered() { return bolusNotDelivered; } @Override public byte getPodMessageCounter() { return podMessageCounter; } @Override public AlertSet getUnacknowledgedAlerts() { return unacknowledgedAlerts; } @Override public byte[] getRawData() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { stream.write(getType().getValue()); stream.write(encodedData); } catch (IOException e) { e.printStackTrace(); return null; } return stream.toByteArray(); } @Override public String toString() { return "StatusResponse{" + "deliveryStatus=" + deliveryStatus + ", podProgressStatus=" + podProgressStatus + ", timeActive=" + timeActive + ", reservoirLevel=" + reservoirLevel + ", ticksDelivered=" + ticksDelivered + ", insulinDelivered=" + insulinDelivered + ", bolusNotDelivered=" + bolusNotDelivered + ", podMessageCounter=" + podMessageCounter + ", unacknowledgedAlerts=" + unacknowledgedAlerts + ", encodedData=" + ByteUtil.shortHexStringWithoutSpaces(encodedData) + '}'; } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/nonuniquetaxonomymappings/IFormUILogicCode.java
2217
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.nonuniquetaxonomymappings; public interface IFormUILogicCode { // No methods yet. }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/domain/OPDSpasticityAssessTreatVoAssembler.java
26598
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.generalmedical.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Sean Nesbitt */ public class OPDSpasticityAssessTreatVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVo copy(ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObjectDest, ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_OPDSpasticityAssessTreat(valueObjectSrc.getID_OPDSpasticityAssessTreat()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // TreatGoals valueObjectDest.setTreatGoals(valueObjectSrc.getTreatGoals()); // TreatmentPlan valueObjectDest.setTreatmentPlan(valueObjectSrc.getTreatmentPlan()); // BotulismTreatment valueObjectDest.setBotulismTreatment(valueObjectSrc.getBotulismTreatment()); // JointContracture valueObjectDest.setJointContracture(valueObjectSrc.getJointContracture()); // LimbFinding valueObjectDest.setLimbFinding(valueObjectSrc.getLimbFinding()); // CareContext valueObjectDest.setCareContext(valueObjectSrc.getCareContext()); // AuthoringInformation valueObjectDest.setAuthoringInformation(valueObjectSrc.getAuthoringInformation()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.medical.domain.objects.OPDSpasticityAssessTreat objects. */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(java.util.Set domainObjectSet) { return createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.medical.domain.objects.OPDSpasticityAssessTreat objects. */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(DomainObjectMap map, java.util.Set domainObjectSet) { ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voList = new ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject = (ims.medical.domain.objects.OPDSpasticityAssessTreat) iterator.next(); ims.generalmedical.vo.OPDSpasticityAssessTreatVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.medical.domain.objects.OPDSpasticityAssessTreat objects. */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(java.util.List domainObjectList) { return createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.medical.domain.objects.OPDSpasticityAssessTreat objects. */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection createOPDSpasticityAssessTreatVoCollectionFromOPDSpasticityAssessTreat(DomainObjectMap map, java.util.List domainObjectList) { ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voList = new ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject = (ims.medical.domain.objects.OPDSpasticityAssessTreat) domainObjectList.get(i); ims.generalmedical.vo.OPDSpasticityAssessTreatVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.medical.domain.objects.OPDSpasticityAssessTreat set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractOPDSpasticityAssessTreatSet(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voCollection) { return extractOPDSpasticityAssessTreatSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractOPDSpasticityAssessTreatSet(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.generalmedical.vo.OPDSpasticityAssessTreatVo vo = voCollection.get(i); ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject = OPDSpasticityAssessTreatVoAssembler.extractOPDSpasticityAssessTreat(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.medical.domain.objects.OPDSpasticityAssessTreat list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractOPDSpasticityAssessTreatList(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voCollection) { return extractOPDSpasticityAssessTreatList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractOPDSpasticityAssessTreatList(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.generalmedical.vo.OPDSpasticityAssessTreatVo vo = voCollection.get(i); ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject = OPDSpasticityAssessTreatVoAssembler.extractOPDSpasticityAssessTreat(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.medical.domain.objects.OPDSpasticityAssessTreat object. * @param domainObject ims.medical.domain.objects.OPDSpasticityAssessTreat */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVo create(ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.medical.domain.objects.OPDSpasticityAssessTreat object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVo create(DomainObjectMap map, ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObject = (ims.generalmedical.vo.OPDSpasticityAssessTreatVo) map.getValueObject(domainObject, ims.generalmedical.vo.OPDSpasticityAssessTreatVo.class); if ( null == valueObject ) { valueObject = new ims.generalmedical.vo.OPDSpasticityAssessTreatVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.medical.domain.objects.OPDSpasticityAssessTreat */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVo insert(ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObject, ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.medical.domain.objects.OPDSpasticityAssessTreat */ public static ims.generalmedical.vo.OPDSpasticityAssessTreatVo insert(DomainObjectMap map, ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObject, ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_OPDSpasticityAssessTreat(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // TreatGoals valueObject.setTreatGoals(ims.generalmedical.vo.domain.OPDSpasticityAssessTreatGoalVoAssembler.createOPDSpasticityAssessTreatGoalVoCollectionFromOPDSpasAssessTreatGoal(map, domainObject.getTreatGoals()) ); // TreatmentPlan java.util.List listTreatmentPlan = domainObject.getTreatmentPlan(); ims.spinalinjuries.vo.lookups.SATreatmentPlanCollection TreatmentPlan = new ims.spinalinjuries.vo.lookups.SATreatmentPlanCollection(); for(java.util.Iterator iterator = listTreatmentPlan.iterator(); iterator.hasNext(); ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; ims.domain.lookups.LookupInstance instance = (ims.domain.lookups.LookupInstance) iterator.next(); if (instance.getImage() != null) { img = new ims.framework.utils.ImagePath(instance.getImage().getImageId(), instance.getImage().getImagePath()); } else { img = null; } color = instance.getColor(); if (color != null) color.getValue(); ims.spinalinjuries.vo.lookups.SATreatmentPlan voInstance = new ims.spinalinjuries.vo.lookups.SATreatmentPlan(instance.getId(),instance.getText(), instance.isActive(), null, img, color); ims.spinalinjuries.vo.lookups.SATreatmentPlan parentVoInstance = voInstance; ims.domain.lookups.LookupInstance parent = instance.getParent(); while (parent != null) { if (parent.getImage() != null) { img = new ims.framework.utils.ImagePath(parent.getImage().getImageId(), parent.getImage().getImagePath()); } else { img = null; } color = parent.getColor(); if (color != null) color.getValue(); parentVoInstance.setParent(new ims.spinalinjuries.vo.lookups.SATreatmentPlan(parent.getId(),parent.getText(), parent.isActive(), null, img, color)); parentVoInstance = parentVoInstance.getParent(); parent = parent.getParent(); } TreatmentPlan.add(voInstance); } valueObject.setTreatmentPlan( TreatmentPlan ); // BotulismTreatment java.util.List listBotulismTreatment = domainObject.getBotulismTreatment(); ims.spinalinjuries.vo.lookups.SABotulinmCollection BotulismTreatment = new ims.spinalinjuries.vo.lookups.SABotulinmCollection(); for(java.util.Iterator iterator = listBotulismTreatment.iterator(); iterator.hasNext(); ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; ims.domain.lookups.LookupInstance instance = (ims.domain.lookups.LookupInstance) iterator.next(); if (instance.getImage() != null) { img = new ims.framework.utils.ImagePath(instance.getImage().getImageId(), instance.getImage().getImagePath()); } else { img = null; } color = instance.getColor(); if (color != null) color.getValue(); ims.spinalinjuries.vo.lookups.SABotulinm voInstance = new ims.spinalinjuries.vo.lookups.SABotulinm(instance.getId(),instance.getText(), instance.isActive(), null, img, color); ims.spinalinjuries.vo.lookups.SABotulinm parentVoInstance = voInstance; ims.domain.lookups.LookupInstance parent = instance.getParent(); while (parent != null) { if (parent.getImage() != null) { img = new ims.framework.utils.ImagePath(parent.getImage().getImageId(), parent.getImage().getImagePath()); } else { img = null; } color = parent.getColor(); if (color != null) color.getValue(); parentVoInstance.setParent(new ims.spinalinjuries.vo.lookups.SABotulinm(parent.getId(),parent.getText(), parent.isActive(), null, img, color)); parentVoInstance = parentVoInstance.getParent(); parent = parent.getParent(); } BotulismTreatment.add(voInstance); } valueObject.setBotulismTreatment( BotulismTreatment ); // JointContracture valueObject.setJointContracture(domainObject.getJointContracture()); // LimbFinding valueObject.setLimbFinding(ims.generalmedical.vo.domain.OPDSpasAssLimbsVoAssembler.createOPDSpasAssLimbsVoCollectionFromOPDSpasAssLimbs(map, domainObject.getLimbFinding()) ); // CareContext valueObject.setCareContext(ims.core.vo.domain.CareContextShortVoAssembler.create(map, domainObject.getCareContext()) ); // AuthoringInformation valueObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInformation()) ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.medical.domain.objects.OPDSpasticityAssessTreat extractOPDSpasticityAssessTreat(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObject) { return extractOPDSpasticityAssessTreat(domainFactory, valueObject, new HashMap()); } public static ims.medical.domain.objects.OPDSpasticityAssessTreat extractOPDSpasticityAssessTreat(ims.domain.ILightweightDomainFactory domainFactory, ims.generalmedical.vo.OPDSpasticityAssessTreatVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_OPDSpasticityAssessTreat(); ims.medical.domain.objects.OPDSpasticityAssessTreat domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.medical.domain.objects.OPDSpasticityAssessTreat)domMap.get(valueObject); } // ims.generalmedical.vo.OPDSpasticityAssessTreatVo ID_OPDSpasticityAssessTreat field is unknown domainObject = new ims.medical.domain.objects.OPDSpasticityAssessTreat(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_OPDSpasticityAssessTreat()); if (domMap.get(key) != null) { return (ims.medical.domain.objects.OPDSpasticityAssessTreat)domMap.get(key); } domainObject = (ims.medical.domain.objects.OPDSpasticityAssessTreat) domainFactory.getDomainObject(ims.medical.domain.objects.OPDSpasticityAssessTreat.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_OPDSpasticityAssessTreat()); domainObject.setTreatGoals(ims.generalmedical.vo.domain.OPDSpasticityAssessTreatGoalVoAssembler.extractOPDSpasAssessTreatGoalSet(domainFactory, valueObject.getTreatGoals(), domainObject.getTreatGoals(), domMap)); ims.spinalinjuries.vo.lookups.SATreatmentPlanCollection collection2 = valueObject.getTreatmentPlan(); java.util.List domainTreatmentPlan = domainObject.getTreatmentPlan();; int collection2Size=0; if (collection2 == null) { domainTreatmentPlan = new java.util.ArrayList(0); } else { collection2Size = collection2.size(); } for(int i=0; i<collection2Size; i++) { int instanceId = collection2.get(i).getID(); ims.domain.lookups.LookupInstanceRef dom =new ims.domain.lookups.LookupInstanceRef(domainFactory.getLookupInstance(instanceId)); int domIdx = domainTreatmentPlan.indexOf(dom); if (domIdx == -1) { domainTreatmentPlan.add(i, dom); } else if (i != domIdx && i < domainTreatmentPlan.size()) { Object tmp = domainTreatmentPlan.get(i); domainTreatmentPlan.set(i, domainTreatmentPlan.get(domIdx)); domainTreatmentPlan.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int j2 = domainTreatmentPlan.size(); while (j2 > collection2Size) { domainTreatmentPlan.remove(j2-1); j2 = domainTreatmentPlan.size(); } domainObject.setTreatmentPlan(domainTreatmentPlan); ims.spinalinjuries.vo.lookups.SABotulinmCollection collection3 = valueObject.getBotulismTreatment(); java.util.List domainBotulismTreatment = domainObject.getBotulismTreatment();; int collection3Size=0; if (collection3 == null) { domainBotulismTreatment = new java.util.ArrayList(0); } else { collection3Size = collection3.size(); } for(int i=0; i<collection3Size; i++) { int instanceId = collection3.get(i).getID(); ims.domain.lookups.LookupInstanceRef dom =new ims.domain.lookups.LookupInstanceRef(domainFactory.getLookupInstance(instanceId)); int domIdx = domainBotulismTreatment.indexOf(dom); if (domIdx == -1) { domainBotulismTreatment.add(i, dom); } else if (i != domIdx && i < domainBotulismTreatment.size()) { Object tmp = domainBotulismTreatment.get(i); domainBotulismTreatment.set(i, domainBotulismTreatment.get(domIdx)); domainBotulismTreatment.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int j3 = domainBotulismTreatment.size(); while (j3 > collection3Size) { domainBotulismTreatment.remove(j3-1); j3 = domainBotulismTreatment.size(); } domainObject.setBotulismTreatment(domainBotulismTreatment); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getJointContracture() != null && valueObject.getJointContracture().equals("")) { valueObject.setJointContracture(null); } domainObject.setJointContracture(valueObject.getJointContracture()); domainObject.setLimbFinding(ims.generalmedical.vo.domain.OPDSpasAssLimbsVoAssembler.extractOPDSpasAssLimbsSet(domainFactory, valueObject.getLimbFinding(), domainObject.getLimbFinding(), domMap)); // SaveAsRefVO - treated as a refVo in extract methods ims.core.admin.domain.objects.CareContext value6 = null; if ( null != valueObject.getCareContext() ) { if (valueObject.getCareContext().getBoId() == null) { if (domMap.get(valueObject.getCareContext()) != null) { value6 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getCareContext()); } } else { value6 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getCareContext().getBoId()); } } domainObject.setCareContext(value6); domainObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.extractAuthoringInformation(domainFactory, valueObject.getAuthoringInformation(), domMap)); return domainObject; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/lookups/SkinWoundBed.java
4809
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class SkinWoundBed extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public SkinWoundBed() { super(); } public SkinWoundBed(int id) { super(id, "", true); } public SkinWoundBed(int id, String text, boolean active) { super(id, text, active, null, null, null); } public SkinWoundBed(int id, String text, boolean active, SkinWoundBed parent, Image image) { super(id, text, active, parent, image); } public SkinWoundBed(int id, String text, boolean active, SkinWoundBed parent, Image image, Color color) { super(id, text, active, parent, image, color); } public SkinWoundBed(int id, String text, boolean active, SkinWoundBed parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static SkinWoundBed buildLookup(ims.vo.LookupInstanceBean bean) { return new SkinWoundBed(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (SkinWoundBed)super.getParentInstance(); } public SkinWoundBed getParent() { return (SkinWoundBed)super.getParentInstance(); } public void setParent(SkinWoundBed parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); SkinWoundBed[] typedChildren = new SkinWoundBed[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (SkinWoundBed)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof SkinWoundBed) { super.addChild((SkinWoundBed)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof SkinWoundBed) { super.removeChild((SkinWoundBed)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { SkinWoundBedCollection result = new SkinWoundBedCollection(); return result; } public static SkinWoundBed[] getNegativeInstances() { return new SkinWoundBed[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static SkinWoundBed getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static SkinWoundBed getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1001029; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/refman/vo/domain/OutcomeAcceptedDetailsVoAssembler.java
20586
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.RefMan.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Cristian Belciug */ public class OutcomeAcceptedDetailsVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVo copy(ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObjectDest, ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_OutcomeAcceptedDetails(valueObjectSrc.getID_OutcomeAcceptedDetails()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // ActionRequired valueObjectDest.setActionRequired(valueObjectSrc.getActionRequired()); // OPA valueObjectDest.setOPA(valueObjectSrc.getOPA()); // Comments valueObjectDest.setComments(valueObjectSrc.getComments()); // LinkedOPA valueObjectDest.setLinkedOPA(valueObjectSrc.getLinkedOPA()); // LinkedDiagnostics valueObjectDest.setLinkedDiagnostics(valueObjectSrc.getLinkedDiagnostics()); // WaitingList valueObjectDest.setWaitingList(valueObjectSrc.getWaitingList()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.RefMan.domain.objects.OutcomeAcceptedDetails objects. */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(java.util.Set domainObjectSet) { return createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.RefMan.domain.objects.OutcomeAcceptedDetails objects. */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(DomainObjectMap map, java.util.Set domainObjectSet) { ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voList = new ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject = (ims.RefMan.domain.objects.OutcomeAcceptedDetails) iterator.next(); ims.RefMan.vo.OutcomeAcceptedDetailsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.RefMan.domain.objects.OutcomeAcceptedDetails objects. */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(java.util.List domainObjectList) { return createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.RefMan.domain.objects.OutcomeAcceptedDetails objects. */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection createOutcomeAcceptedDetailsVoCollectionFromOutcomeAcceptedDetails(DomainObjectMap map, java.util.List domainObjectList) { ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voList = new ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject = (ims.RefMan.domain.objects.OutcomeAcceptedDetails) domainObjectList.get(i); ims.RefMan.vo.OutcomeAcceptedDetailsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.RefMan.domain.objects.OutcomeAcceptedDetails set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractOutcomeAcceptedDetailsSet(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voCollection) { return extractOutcomeAcceptedDetailsSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractOutcomeAcceptedDetailsSet(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.RefMan.vo.OutcomeAcceptedDetailsVo vo = voCollection.get(i); ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject = OutcomeAcceptedDetailsVoAssembler.extractOutcomeAcceptedDetails(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.RefMan.domain.objects.OutcomeAcceptedDetails list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractOutcomeAcceptedDetailsList(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voCollection) { return extractOutcomeAcceptedDetailsList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractOutcomeAcceptedDetailsList(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.RefMan.vo.OutcomeAcceptedDetailsVo vo = voCollection.get(i); ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject = OutcomeAcceptedDetailsVoAssembler.extractOutcomeAcceptedDetails(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.RefMan.domain.objects.OutcomeAcceptedDetails object. * @param domainObject ims.RefMan.domain.objects.OutcomeAcceptedDetails */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVo create(ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.RefMan.domain.objects.OutcomeAcceptedDetails object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVo create(DomainObjectMap map, ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObject = (ims.RefMan.vo.OutcomeAcceptedDetailsVo) map.getValueObject(domainObject, ims.RefMan.vo.OutcomeAcceptedDetailsVo.class); if ( null == valueObject ) { valueObject = new ims.RefMan.vo.OutcomeAcceptedDetailsVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.RefMan.domain.objects.OutcomeAcceptedDetails */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVo insert(ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObject, ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.RefMan.domain.objects.OutcomeAcceptedDetails */ public static ims.RefMan.vo.OutcomeAcceptedDetailsVo insert(DomainObjectMap map, ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObject, ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_OutcomeAcceptedDetails(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // ActionRequired ims.domain.lookups.LookupInstance instance1 = domainObject.getActionRequired(); if ( null != instance1 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance1.getImage() != null) { img = new ims.framework.utils.ImagePath(instance1.getImage().getImageId(), instance1.getImage().getImagePath()); } color = instance1.getColor(); if (color != null) color.getValue(); ims.RefMan.vo.lookups.AcceptedActionsRequired voLookup1 = new ims.RefMan.vo.lookups.AcceptedActionsRequired(instance1.getId(),instance1.getText(), instance1.isActive(), null, img, color); ims.RefMan.vo.lookups.AcceptedActionsRequired parentVoLookup1 = voLookup1; ims.domain.lookups.LookupInstance parent1 = instance1.getParent(); while (parent1 != null) { if (parent1.getImage() != null) { img = new ims.framework.utils.ImagePath(parent1.getImage().getImageId(), parent1.getImage().getImagePath() ); } else { img = null; } color = parent1.getColor(); if (color != null) color.getValue(); parentVoLookup1.setParent(new ims.RefMan.vo.lookups.AcceptedActionsRequired(parent1.getId(),parent1.getText(), parent1.isActive(), null, img, color)); parentVoLookup1 = parentVoLookup1.getParent(); parent1 = parent1.getParent(); } valueObject.setActionRequired(voLookup1); } // OPA valueObject.setOPA(ims.RefMan.vo.domain.OPAVoAssembler.create(map, domainObject.getOPA()) ); // Comments valueObject.setComments(domainObject.getComments()); // LinkedOPA valueObject.setLinkedOPA(ims.scheduling.vo.domain.FutureAppointmentDetailsVoAssembler.create(map, domainObject.getLinkedOPA()) ); // LinkedDiagnostics valueObject.setLinkedDiagnostics(ims.RefMan.vo.domain.LinkedDiagnosticVoAssembler.createLinkedDiagnosticVoCollectionFromLinkedDiagnostic(map, domainObject.getLinkedDiagnostics()) ); // WaitingList valueObject.setWaitingList(ims.RefMan.vo.domain.PatientElectiveListAddLaterVoAssembler.create(map, domainObject.getWaitingList()) ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.RefMan.domain.objects.OutcomeAcceptedDetails extractOutcomeAcceptedDetails(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObject) { return extractOutcomeAcceptedDetails(domainFactory, valueObject, new HashMap()); } public static ims.RefMan.domain.objects.OutcomeAcceptedDetails extractOutcomeAcceptedDetails(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.OutcomeAcceptedDetailsVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_OutcomeAcceptedDetails(); ims.RefMan.domain.objects.OutcomeAcceptedDetails domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.RefMan.domain.objects.OutcomeAcceptedDetails)domMap.get(valueObject); } // ims.RefMan.vo.OutcomeAcceptedDetailsVo ID_OutcomeAcceptedDetails field is unknown domainObject = new ims.RefMan.domain.objects.OutcomeAcceptedDetails(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_OutcomeAcceptedDetails()); if (domMap.get(key) != null) { return (ims.RefMan.domain.objects.OutcomeAcceptedDetails)domMap.get(key); } domainObject = (ims.RefMan.domain.objects.OutcomeAcceptedDetails) domainFactory.getDomainObject(ims.RefMan.domain.objects.OutcomeAcceptedDetails.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_OutcomeAcceptedDetails()); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value1 = null; if ( null != valueObject.getActionRequired() ) { value1 = domainFactory.getLookupInstance(valueObject.getActionRequired().getID()); } domainObject.setActionRequired(value1); domainObject.setOPA(ims.RefMan.vo.domain.OPAVoAssembler.extractOPA(domainFactory, valueObject.getOPA(), domMap)); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getComments() != null && valueObject.getComments().equals("")) { valueObject.setComments(null); } domainObject.setComments(valueObject.getComments()); domainObject.setLinkedOPA(ims.scheduling.vo.domain.FutureAppointmentDetailsVoAssembler.extractFutureAppointmentDetails(domainFactory, valueObject.getLinkedOPA(), domMap)); domainObject.setLinkedDiagnostics(ims.RefMan.vo.domain.LinkedDiagnosticVoAssembler.extractLinkedDiagnosticList(domainFactory, valueObject.getLinkedDiagnostics(), domainObject.getLinkedDiagnostics(), domMap)); domainObject.setWaitingList(ims.RefMan.vo.domain.PatientElectiveListAddLaterVoAssembler.extractPatientElectiveList(domainFactory, valueObject.getWaitingList(), domMap)); return domainObject; } }
agpl-3.0
xkmato/mage
src/main/java/io/rapidpro/mage/task/SentryTestTask.java
957
package io.rapidpro.mage.task; import com.google.common.collect.ImmutableMultimap; import io.dropwizard.servlets.tasks.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintWriter; /** * Task to test Sentry */ public class SentryTestTask extends Task { protected static final Logger log = LoggerFactory.getLogger(SentryTestTask.class); public SentryTestTask() { super("sentry-test"); } /** * @see io.dropwizard.servlets.tasks.Task#execute(com.google.common.collect.ImmutableMultimap, java.io.PrintWriter) */ @Override public void execute(ImmutableMultimap<String, String> params, PrintWriter output) throws Exception { output.println("Testing sentry..."); try { throw new RuntimeException("This is an exception"); } catch (Exception e) { log.error("Testing Sentry", e); } output.println("Done!"); } }
agpl-3.0
gama-platform/gama.cloud
ummisco.gama.ui.navigator_web/src/ummisco/gama/ui/navigator/GamaNavigatorNewMenu.java
3034
/********************************************************************************************* * * 'GamaNavigatorNewMenu.java, in plugin ummisco.gama.ui.navigator, is part of the source code of the GAMA modeling and * simulation platform. (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners * * Visit https://github.com/gama-platform/gama for license information and developers contact. * * **********************************************************************************************/ package ummisco.gama.ui.navigator; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import ummisco.gama.ui.resources.GamaIcons; /** * Class GamaNavigatorMenus. * * @author drogoul * @since 8 mars 2015 * */ public class GamaNavigatorNewMenu extends GamaNavigatorMenu { public GamaNavigatorNewMenu(final IStructuredSelection selection) { this.selection = selection; } IStructuredSelection selection; private final SelectionListener newModel = new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { openWizard("msi.gama.gui.wizards.NewFileWizard", selection); } }; private final SelectionListener newExperiment = new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { openWizard("msi.gama.gui.wizards.NewExperimentWizard", selection); } }; private final SelectionListener newProject = new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { openWizard("msi.gama.gui.wizards.newProjectWizard", selection); } }; private final SelectionListener newFolder = new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { openWizard("org.eclipse.ui.wizards.new.folder", selection); } }; private final SelectionListener newTestExperiment = new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { openWizard("msi.gama.gui.wizards.NewTestExperimentWizard", selection); } }; // private final SelectionListener newOther = new SelectionAdapter() { // // @Override // public void widgetSelected(final SelectionEvent e) { // openWizard("org.eclipse.ui.internal.dialogs.NewWizard", selection); // } // // }; @Override protected void fillMenu() { action("New Model file...", newModel, GamaIcons.create("navigator/new.model2").image()); action("New Experiment file...", newExperiment, GamaIcons.create("navigator/new.model2").image()); action("New Project...", newProject, GamaIcons.create("navigator/new.project2").image()); sep(); action("New Test Experiment file...", newTestExperiment, GamaIcons.create("navigator/new.model2").image()); sep(); action("New Folder...", newFolder, GamaIcons.create("navigator/new.folder2").image()); // sep(); // action("Other...", newOther, GamaIcons.create("navigator/navigator.new2").image()); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/therapies/vo/EnvironmentalVisitShortVo.java
10289
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.therapies.vo; /** * Linked to therapies.homeAndEnvironmentalVisit.EnvironmentalVisit business object (ID: 1019100096). */ public class EnvironmentalVisitShortVo extends ims.therapies.homeandenvironmentalvisit.vo.EnvironmentalVisitRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public EnvironmentalVisitShortVo() { } public EnvironmentalVisitShortVo(Integer id, int version) { super(id, version); } public EnvironmentalVisitShortVo(ims.therapies.vo.beans.EnvironmentalVisitShortVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.clinicalcontact = bean.getClinicalContact() == null ? null : bean.getClinicalContact().buildVo(); this.authoringcp = bean.getAuthoringCP() == null ? null : bean.getAuthoringCP().buildVo(); this.authoringdatetime = bean.getAuthoringDateTime() == null ? null : bean.getAuthoringDateTime().buildDateTime(); this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.therapies.vo.beans.EnvironmentalVisitShortVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.clinicalcontact = bean.getClinicalContact() == null ? null : bean.getClinicalContact().buildVo(map); this.authoringcp = bean.getAuthoringCP() == null ? null : bean.getAuthoringCP().buildVo(map); this.authoringdatetime = bean.getAuthoringDateTime() == null ? null : bean.getAuthoringDateTime().buildDateTime(); this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.therapies.vo.beans.EnvironmentalVisitShortVoBean bean = null; if(map != null) bean = (ims.therapies.vo.beans.EnvironmentalVisitShortVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.therapies.vo.beans.EnvironmentalVisitShortVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CLINICALCONTACT")) return getClinicalContact(); if(fieldName.equals("AUTHORINGCP")) return getAuthoringCP(); if(fieldName.equals("AUTHORINGDATETIME")) return getAuthoringDateTime(); if(fieldName.equals("CARECONTEXT")) return getCareContext(); return super.getFieldValueByFieldName(fieldName); } public boolean getClinicalContactIsNotNull() { return this.clinicalcontact != null; } public ims.core.vo.ClinicalContactShortVo getClinicalContact() { return this.clinicalcontact; } public void setClinicalContact(ims.core.vo.ClinicalContactShortVo value) { this.isValidated = false; this.clinicalcontact = value; } public boolean getAuthoringCPIsNotNull() { return this.authoringcp != null; } public ims.core.vo.Hcp getAuthoringCP() { return this.authoringcp; } public void setAuthoringCP(ims.core.vo.Hcp value) { this.isValidated = false; this.authoringcp = value; } public boolean getAuthoringDateTimeIsNotNull() { return this.authoringdatetime != null; } public ims.framework.utils.DateTime getAuthoringDateTime() { return this.authoringdatetime; } public void setAuthoringDateTime(ims.framework.utils.DateTime value) { this.isValidated = false; this.authoringdatetime = value; } public boolean getCareContextIsNotNull() { return this.carecontext != null; } public ims.core.admin.vo.CareContextRefVo getCareContext() { return this.carecontext; } public void setCareContext(ims.core.admin.vo.CareContextRefVo value) { this.isValidated = false; this.carecontext = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } if(this.authoringcp != null) { if(!this.authoringcp.isValidated()) { this.isBusy = false; return false; } } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.authoringcp == null) listOfErrors.add("AuthoringCP is mandatory"); if(this.authoringcp != null) { String[] listOfOtherErrors = this.authoringcp.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.authoringdatetime == null) listOfErrors.add("AuthoringDateTime is mandatory"); if(this.carecontext == null) listOfErrors.add("CareContext is mandatory"); int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; EnvironmentalVisitShortVo clone = new EnvironmentalVisitShortVo(this.id, this.version); if(this.clinicalcontact == null) clone.clinicalcontact = null; else clone.clinicalcontact = (ims.core.vo.ClinicalContactShortVo)this.clinicalcontact.clone(); if(this.authoringcp == null) clone.authoringcp = null; else clone.authoringcp = (ims.core.vo.Hcp)this.authoringcp.clone(); if(this.authoringdatetime == null) clone.authoringdatetime = null; else clone.authoringdatetime = (ims.framework.utils.DateTime)this.authoringdatetime.clone(); clone.carecontext = this.carecontext; clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(EnvironmentalVisitShortVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A EnvironmentalVisitShortVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((EnvironmentalVisitShortVo)obj).getBoId() == null) return -1; return this.id.compareTo(((EnvironmentalVisitShortVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.clinicalcontact != null) count++; if(this.authoringcp != null) count++; if(this.authoringdatetime != null) count++; if(this.carecontext != null) count++; return count; } public int countValueObjectFields() { return 4; } protected ims.core.vo.ClinicalContactShortVo clinicalcontact; protected ims.core.vo.Hcp authoringcp; protected ims.framework.utils.DateTime authoringdatetime; protected ims.core.admin.vo.CareContextRefVo carecontext; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
bitsquare/bitsquare
core/src/main/java/bisq/core/offer/OfferRestrictions.java
2124
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.offer; import bisq.core.offer.bisq_v1.OfferPayload; import bisq.common.app.Capabilities; import bisq.common.app.Capability; import bisq.common.config.Config; import bisq.common.util.Utilities; import org.bitcoinj.core.Coin; import java.util.Date; import java.util.GregorianCalendar; import java.util.Map; public class OfferRestrictions { // The date when traders who have not upgraded to a Tor v3 Node Address cannot take offers and their offers become // invisible. private static final Date REQUIRE_TOR_NODE_ADDRESS_V3_DATE = Utilities.getUTCDate(2021, GregorianCalendar.AUGUST, 15); public static boolean requiresNodeAddressUpdate() { return new Date().after(REQUIRE_TOR_NODE_ADDRESS_V3_DATE) && !Config.baseCurrencyNetwork().isRegtest(); } public static Coin TOLERATED_SMALL_TRADE_AMOUNT = Coin.parseCoin("0.01"); static boolean hasOfferMandatoryCapability(Offer offer, Capability mandatoryCapability) { Map<String, String> extraDataMap = offer.getExtraDataMap(); if (extraDataMap != null && extraDataMap.containsKey(OfferPayload.CAPABILITIES)) { String commaSeparatedOrdinals = extraDataMap.get(OfferPayload.CAPABILITIES); Capabilities capabilities = Capabilities.fromStringList(commaSeparatedOrdinals); return Capabilities.hasMandatoryCapability(capabilities, mandatoryCapability); } return false; } }
agpl-3.0
ebonnet/Silverpeas-Core
core-web/src/main/java/org/silverpeas/core/webapi/attachment/SimpleDocumentEntity.java
5424
/* * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection withWriter Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.webapi.attachment; import java.net.URI; import java.net.URISyntaxException; import javax.xml.bind.annotation.XmlElement; import org.silverpeas.core.webapi.base.WebEntity; import org.silverpeas.core.contribution.attachment.AttachmentException; import org.silverpeas.core.contribution.attachment.model.SimpleDocument; import org.silverpeas.core.util.URLUtil; /** * * @author ehugonnet */ public class SimpleDocumentEntity implements WebEntity { private static final long serialVersionUID = 6578990825699318566L; @XmlElement(required = true) private String id; @XmlElement(required = true) private String instanceId; @XmlElement(required = true) private String fileName; @XmlElement(defaultValue = "") private String description; @XmlElement(defaultValue = "") private String contentType; @XmlElement(defaultValue = "0") private long creationDate; @XmlElement(defaultValue = "") private String createdBy; @XmlElement(defaultValue = "0") private long updateDate; @XmlElement(defaultValue = "") private String updatedBy; @XmlElement(defaultValue = "0") private long size; @XmlElement(defaultValue = "") private String title; @XmlElement(defaultValue = "") private String lang; @XmlElement(required = true) private URI uri; @XmlElement(required = true) private String icon; @XmlElement(required = true) private String permalink; @XmlElement(defaultValue = "") private String downloadUrl; @XmlElement(defaultValue = "") private String comment; @XmlElement(defaultValue = "false") private String versioned; public static SimpleDocumentEntity fromAttachment(SimpleDocument document) { SimpleDocumentEntity entity = new SimpleDocumentEntity(); try { entity.uri = new URI(URLUtil.getSimpleURL(URLUtil.URL_FILE, document.getId())); } catch (URISyntaxException e) { throw new AttachmentException("AttachmentEntity.fromAttachment(", AttachmentException.ERROR, "Couldn't build the URI to the attachment", e); } entity.id = document.getId(); entity.instanceId = document.getInstanceId(); entity.fileName = document.getFilename(); entity.description = document.getDescription(); entity.size = document.getSize(); entity.creationDate = document.getCreated().getTime(); entity.createdBy = document.getCreatedBy(); if (document.getUpdated() != null) { entity.updateDate = document.getUpdated().getTime(); } entity.updatedBy = document.getUpdatedBy(); entity.title = document.getTitle(); entity.contentType = document.getContentType(); entity.icon = document.getDisplayIcon(); entity.permalink = URLUtil.getSimpleURL(URLUtil.URL_FILE, document.getId()); entity.downloadUrl = document.getAttachmentURL(); entity.lang = document.getLanguage(); entity.comment = document.getComment(); entity.versioned = String.valueOf(document.isVersioned()); return entity; } /** * Sets a URI to this entity. With this URI, it can then be accessed through the Web. * * @param uri the web entity URI. * @return itself. */ public SimpleDocumentEntity withURI(final URI uri) { this.uri = uri; return this; } @Override public URI getURI() { return this.uri; } public String getId() { return id; } public String getInstanceId() { return instanceId; } public String getFileName() { return fileName; } public String getDescription() { return description; } public String getContentType() { return contentType; } public long getCreationDate() { return creationDate; } public String getCreatedBy() { return createdBy; } public long getUpdateDate() { return updateDate; } public String getUpdatedBy() { return updatedBy; } public long getSize() { return size; } public String getTitle() { return title; } public String getLang() { return lang; } public String getIcon() { return icon; } public String getPermalink() { return permalink; } public String getDownloadUrl() { return downloadUrl; } public String getComment() { return comment; } public String getVersioned() { return versioned; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/edischarge/vo/NeoNatalRefVoCollection.java
5264
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.edischarge.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to eDischarge.NeoNatal business object (ID: 1099100013). */ public class NeoNatalRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<NeoNatalRefVo> { private static final long serialVersionUID = 1L; private ArrayList<NeoNatalRefVo> col = new ArrayList<NeoNatalRefVo>(); public final String getBoClassName() { return "ims.edischarge.domain.objects.NeoNatal"; } public ims.domain.IDomainGetter[] getIDomainGetterItems() { ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()]; col.toArray(result); return result; } public boolean add(NeoNatalRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, NeoNatalRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(NeoNatalRefVo instance) { return col.indexOf(instance); } public NeoNatalRefVo get(int index) { return this.col.get(index); } public boolean set(int index, NeoNatalRefVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(NeoNatalRefVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(NeoNatalRefVo instance) { return indexOf(instance) >= 0; } public Object clone() { NeoNatalRefVoCollection clone = new NeoNatalRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((NeoNatalRefVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { return true; } public String[] validate() { return null; } public NeoNatalRefVo[] toArray() { NeoNatalRefVo[] arr = new NeoNatalRefVo[col.size()]; col.toArray(arr); return arr; } public NeoNatalRefVoCollection sort() { return sort(SortOrder.ASCENDING); } public NeoNatalRefVoCollection sort(SortOrder order) { return sort(new NeoNatalRefVoComparator(order)); } @SuppressWarnings("unchecked") public NeoNatalRefVoCollection sort(Comparator comparator) { Collections.sort(this.col, comparator); return this; } public Iterator<NeoNatalRefVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class NeoNatalRefVoComparator implements Comparator { private int direction = 1; public NeoNatalRefVoComparator() { this(SortOrder.ASCENDING); } public NeoNatalRefVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { this.direction = -1; } } public int compare(Object obj1, Object obj2) { NeoNatalRefVo voObj1 = (NeoNatalRefVo)obj1; NeoNatalRefVo voObj2 = (NeoNatalRefVo)obj2; return direction*(voObj1.compareTo(voObj2)); } } }
agpl-3.0
jar1karp/rstudio
src/gwt/src/org/rstudio/core/client/widget/UIPrefMenuItem.java
2527
/* * UIPrefMenuItem.java * * Copyright (C) 2009-14 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import org.rstudio.core.client.widget.CheckableMenuItem; import org.rstudio.studio.client.workbench.prefs.model.Prefs.PrefValue; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; // A menu item that represents a given value for a given UIPref. Shows a check // when the UIPref is set to the value. Invoking the menu item sets the UIPref // to the value. public class UIPrefMenuItem <T> extends CheckableMenuItem { public UIPrefMenuItem(PrefValue<T> prefValue, T targetValue, String label, UIPrefs uiPrefs) { targetValue_ = targetValue; label_ = label; uiPrefs_ = uiPrefs; prefValue_ = prefValue; prefValue.addValueChangeHandler( new ValueChangeHandler<T>() { @Override public void onValueChange(ValueChangeEvent<T> arg0) { onStateChanged(); } }); onStateChanged(); } @Override public boolean isChecked() { return prefValue_ != null && prefValue_.getValue() == targetValue_; } @Override @SuppressWarnings({ "unchecked" }) public void onInvoked() { if (targetValue_ instanceof Boolean) { // for boolean values, the menu item acts like a toggle Boolean newValue = !(Boolean)prefValue_.getValue(); prefValue_.setGlobalValue((T)newValue, true); } else { // for other value types the menu item always sets to the target value prefValue_.setGlobalValue(targetValue_, true); } uiPrefs_.writeUIPrefs(); } @Override public String getLabel() { return label_ == null ? "" : label_; } T targetValue_; PrefValue<T> prefValue_; UIPrefs uiPrefs_; String label_; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/spinalinjuries/vo/lookups/RehabEquipmentCollection.java
4862
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.spinalinjuries.vo.lookups; import ims.framework.cn.data.TreeModel; import ims.framework.cn.data.TreeNode; import ims.vo.LookupInstanceCollection; import ims.vo.LookupInstVo; public class RehabEquipmentCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel { private static final long serialVersionUID = 1L; public void add(RehabEquipment value) { super.add(value); } public int indexOf(RehabEquipment instance) { return super.indexOf(instance); } public boolean contains(RehabEquipment instance) { return indexOf(instance) >= 0; } public RehabEquipment get(int index) { return (RehabEquipment)super.getIndex(index); } public void remove(RehabEquipment instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public Object clone() { RehabEquipmentCollection newCol = new RehabEquipmentCollection(); RehabEquipment item; for (int i = 0; i < super.size(); i++) { item = this.get(i); newCol.add(new RehabEquipment(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder())); } for (int i = 0; i < newCol.size(); i++) { item = newCol.get(i); if (item.getParent() != null) { int parentIndex = this.indexOf(item.getParent()); if(parentIndex >= 0) item.setParent(newCol.get(parentIndex)); else item.setParent((RehabEquipment)item.getParent().clone()); } } return newCol; } public RehabEquipment getInstance(int instanceId) { return (RehabEquipment)super.getInstanceById(instanceId); } public TreeNode[] getRootNodes() { LookupInstVo[] roots = super.getRoots(); TreeNode[] nodes = new TreeNode[roots.length]; System.arraycopy(roots, 0, nodes, 0, roots.length); return nodes; } public RehabEquipment[] toArray() { RehabEquipment[] arr = new RehabEquipment[this.size()]; super.toArray(arr); return arr; } public static RehabEquipmentCollection buildFromBeanCollection(java.util.Collection beans) { RehabEquipmentCollection coll = new RehabEquipmentCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while(iter.hasNext()) { coll.add(RehabEquipment.buildLookup((ims.vo.LookupInstanceBean)iter.next())); } return coll; } public static RehabEquipmentCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans) { RehabEquipmentCollection coll = new RehabEquipmentCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(RehabEquipment.buildLookup(beans[x])); } return coll; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/clinical/vo/domain/TourniquetIntraOpVoAssembler.java
20601
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:23 * */ package ims.clinical.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Daniel Laffan */ public class TourniquetIntraOpVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.clinical.vo.TourniquetIntraOpVo copy(ims.clinical.vo.TourniquetIntraOpVo valueObjectDest, ims.clinical.vo.TourniquetIntraOpVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_TourniquetIntraOp(valueObjectSrc.getID_TourniquetIntraOp()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // TheatreAppointment valueObjectDest.setTheatreAppointment(valueObjectSrc.getTheatreAppointment()); // Site valueObjectDest.setSite(valueObjectSrc.getSite()); // Inflated valueObjectDest.setInflated(valueObjectSrc.getInflated()); // Deflated valueObjectDest.setDeflated(valueObjectSrc.getDeflated()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.clinical.domain.objects.TourniquetIntraOp objects. */ public static ims.clinical.vo.TourniquetIntraOpVoCollection createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(java.util.Set domainObjectSet) { return createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.clinical.domain.objects.TourniquetIntraOp objects. */ public static ims.clinical.vo.TourniquetIntraOpVoCollection createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(DomainObjectMap map, java.util.Set domainObjectSet) { ims.clinical.vo.TourniquetIntraOpVoCollection voList = new ims.clinical.vo.TourniquetIntraOpVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.clinical.domain.objects.TourniquetIntraOp domainObject = (ims.clinical.domain.objects.TourniquetIntraOp) iterator.next(); ims.clinical.vo.TourniquetIntraOpVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.clinical.domain.objects.TourniquetIntraOp objects. */ public static ims.clinical.vo.TourniquetIntraOpVoCollection createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(java.util.List domainObjectList) { return createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.clinical.domain.objects.TourniquetIntraOp objects. */ public static ims.clinical.vo.TourniquetIntraOpVoCollection createTourniquetIntraOpVoCollectionFromTourniquetIntraOp(DomainObjectMap map, java.util.List domainObjectList) { ims.clinical.vo.TourniquetIntraOpVoCollection voList = new ims.clinical.vo.TourniquetIntraOpVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.clinical.domain.objects.TourniquetIntraOp domainObject = (ims.clinical.domain.objects.TourniquetIntraOp) domainObjectList.get(i); ims.clinical.vo.TourniquetIntraOpVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.clinical.domain.objects.TourniquetIntraOp set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractTourniquetIntraOpSet(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVoCollection voCollection) { return extractTourniquetIntraOpSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractTourniquetIntraOpSet(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.clinical.vo.TourniquetIntraOpVo vo = voCollection.get(i); ims.clinical.domain.objects.TourniquetIntraOp domainObject = TourniquetIntraOpVoAssembler.extractTourniquetIntraOp(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.clinical.domain.objects.TourniquetIntraOp list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractTourniquetIntraOpList(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVoCollection voCollection) { return extractTourniquetIntraOpList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractTourniquetIntraOpList(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.clinical.vo.TourniquetIntraOpVo vo = voCollection.get(i); ims.clinical.domain.objects.TourniquetIntraOp domainObject = TourniquetIntraOpVoAssembler.extractTourniquetIntraOp(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.clinical.domain.objects.TourniquetIntraOp object. * @param domainObject ims.clinical.domain.objects.TourniquetIntraOp */ public static ims.clinical.vo.TourniquetIntraOpVo create(ims.clinical.domain.objects.TourniquetIntraOp domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.clinical.domain.objects.TourniquetIntraOp object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.clinical.vo.TourniquetIntraOpVo create(DomainObjectMap map, ims.clinical.domain.objects.TourniquetIntraOp domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.clinical.vo.TourniquetIntraOpVo valueObject = (ims.clinical.vo.TourniquetIntraOpVo) map.getValueObject(domainObject, ims.clinical.vo.TourniquetIntraOpVo.class); if ( null == valueObject ) { valueObject = new ims.clinical.vo.TourniquetIntraOpVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.clinical.domain.objects.TourniquetIntraOp */ public static ims.clinical.vo.TourniquetIntraOpVo insert(ims.clinical.vo.TourniquetIntraOpVo valueObject, ims.clinical.domain.objects.TourniquetIntraOp domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.clinical.domain.objects.TourniquetIntraOp */ public static ims.clinical.vo.TourniquetIntraOpVo insert(DomainObjectMap map, ims.clinical.vo.TourniquetIntraOpVo valueObject, ims.clinical.domain.objects.TourniquetIntraOp domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_TourniquetIntraOp(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // TheatreAppointment if (domainObject.getTheatreAppointment() != null) { if(domainObject.getTheatreAppointment() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getTheatreAppointment(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setTheatreAppointment(new ims.scheduling.vo.Booking_AppointmentRefVo(id, -1)); } else { valueObject.setTheatreAppointment(new ims.scheduling.vo.Booking_AppointmentRefVo(domainObject.getTheatreAppointment().getId(), domainObject.getTheatreAppointment().getVersion())); } } // Site ims.domain.lookups.LookupInstance instance2 = domainObject.getSite(); if ( null != instance2 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance2.getImage() != null) { img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath()); } color = instance2.getColor(); if (color != null) color.getValue(); ims.clinical.vo.lookups.TourniquetSite voLookup2 = new ims.clinical.vo.lookups.TourniquetSite(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color); ims.clinical.vo.lookups.TourniquetSite parentVoLookup2 = voLookup2; ims.domain.lookups.LookupInstance parent2 = instance2.getParent(); while (parent2 != null) { if (parent2.getImage() != null) { img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() ); } else { img = null; } color = parent2.getColor(); if (color != null) color.getValue(); parentVoLookup2.setParent(new ims.clinical.vo.lookups.TourniquetSite(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color)); parentVoLookup2 = parentVoLookup2.getParent(); parent2 = parent2.getParent(); } valueObject.setSite(voLookup2); } // Inflated java.util.Date Inflated = domainObject.getInflated(); if ( null != Inflated ) { valueObject.setInflated(new ims.framework.utils.DateTime(Inflated) ); } // Deflated java.util.Date Deflated = domainObject.getDeflated(); if ( null != Deflated ) { valueObject.setDeflated(new ims.framework.utils.DateTime(Deflated) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.clinical.domain.objects.TourniquetIntraOp extractTourniquetIntraOp(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVo valueObject) { return extractTourniquetIntraOp(domainFactory, valueObject, new HashMap()); } public static ims.clinical.domain.objects.TourniquetIntraOp extractTourniquetIntraOp(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.TourniquetIntraOpVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_TourniquetIntraOp(); ims.clinical.domain.objects.TourniquetIntraOp domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.clinical.domain.objects.TourniquetIntraOp)domMap.get(valueObject); } // ims.clinical.vo.TourniquetIntraOpVo ID_TourniquetIntraOp field is unknown domainObject = new ims.clinical.domain.objects.TourniquetIntraOp(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_TourniquetIntraOp()); if (domMap.get(key) != null) { return (ims.clinical.domain.objects.TourniquetIntraOp)domMap.get(key); } domainObject = (ims.clinical.domain.objects.TourniquetIntraOp) domainFactory.getDomainObject(ims.clinical.domain.objects.TourniquetIntraOp.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_TourniquetIntraOp()); ims.scheduling.domain.objects.Booking_Appointment value1 = null; if ( null != valueObject.getTheatreAppointment() ) { if (valueObject.getTheatreAppointment().getBoId() == null) { if (domMap.get(valueObject.getTheatreAppointment()) != null) { value1 = (ims.scheduling.domain.objects.Booking_Appointment)domMap.get(valueObject.getTheatreAppointment()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getTheatreAppointment(); } else { value1 = (ims.scheduling.domain.objects.Booking_Appointment)domainFactory.getDomainObject(ims.scheduling.domain.objects.Booking_Appointment.class, valueObject.getTheatreAppointment().getBoId()); } } domainObject.setTheatreAppointment(value1); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value2 = null; if ( null != valueObject.getSite() ) { value2 = domainFactory.getLookupInstance(valueObject.getSite().getID()); } domainObject.setSite(value2); ims.framework.utils.DateTime dateTime3 = valueObject.getInflated(); java.util.Date value3 = null; if ( dateTime3 != null ) { value3 = dateTime3.getJavaDate(); } domainObject.setInflated(value3); ims.framework.utils.DateTime dateTime4 = valueObject.getDeflated(); java.util.Date value4 = null; if ( dateTime4 != null ) { value4 = dateTime4.getJavaDate(); } domainObject.setDeflated(value4); return domainObject; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/careplantemplates/BaseAccessLogic.java
4273
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.forms.careplantemplates; import java.io.Serializable; import ims.framework.Context; import ims.framework.FormName; import ims.framework.FormAccessLogic; public class BaseAccessLogic extends FormAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public final void setContext(Context context, FormName formName) { form = new CurrentForm(new GlobalContext(context), new CurrentForms()); engine = new CurrentEngine(formName); } public boolean isAccessible() { return true; } public boolean isReadOnly() { return false; } public CurrentEngine engine; public CurrentForm form; public final static class CurrentForm implements Serializable { private static final long serialVersionUID = 1L; CurrentForm(GlobalContext globalcontext, CurrentForms forms) { this.globalcontext = globalcontext; this.forms = forms; } public final GlobalContext getGlobalContext() { return globalcontext; } public final CurrentForms getForms() { return forms; } private GlobalContext globalcontext; private CurrentForms forms; } public final static class CurrentEngine implements Serializable { private static final long serialVersionUID = 1L; CurrentEngine(FormName formName) { this.formName = formName; } public final FormName getFormName() { return formName; } private FormName formName; } public static final class CurrentForms implements Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; protected LocalFormName(int value) { super(value); } } private CurrentForms() { Nursing = new NursingForms(); } public final class NursingForms implements Serializable { private static final long serialVersionUID = 1L; private NursingForms() { CarePlanTemplateDetail = new LocalFormName(104100); } public final FormName CarePlanTemplateDetail; } public NursingForms Nursing; } }
agpl-3.0
gotodeepak1122/enviroCar-server
rest/src/main/java/org/envirocar/server/rest/encoding/ShapefileTrackEncoder.java
1139
/* * Copyright (C) 2013 The enviroCar project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.envirocar.server.rest.encoding; import java.io.File; import javax.ws.rs.core.MediaType; import org.envirocar.server.core.exception.TrackTooLongException; import org.envirocar.server.rest.rights.AccessRights; /** * TODO JavaDoc * * @author Benjamin Pross */ public interface ShapefileTrackEncoder<T> { File encodeShapefile(T t, AccessRights rights, MediaType mt) throws TrackTooLongException; }
agpl-3.0
bitsquare/bitsquare
p2p/src/main/java/bisq/network/p2p/peers/keepalive/messages/Ping.java
2086
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.network.p2p.peers.keepalive.messages; import bisq.common.app.Version; import bisq.common.proto.network.NetworkEnvelope; import lombok.EqualsAndHashCode; import lombok.Value; @EqualsAndHashCode(callSuper = true) @Value public final class Ping extends NetworkEnvelope implements KeepAliveMessage { private final int nonce; private final int lastRoundTripTime; public Ping(int nonce, int lastRoundTripTime) { this(nonce, lastRoundTripTime, Version.getP2PMessageVersion()); } /////////////////////////////////////////////////////////////////////////////////////////// // PROTO BUFFER /////////////////////////////////////////////////////////////////////////////////////////// private Ping(int nonce, int lastRoundTripTime, int messageVersion) { super(messageVersion); this.nonce = nonce; this.lastRoundTripTime = lastRoundTripTime; } @Override public protobuf.NetworkEnvelope toProtoNetworkEnvelope() { return getNetworkEnvelopeBuilder() .setPing(protobuf.Ping.newBuilder() .setNonce(nonce) .setLastRoundTripTime(lastRoundTripTime)) .build(); } public static Ping fromProto(protobuf.Ping proto, int messageVersion) { return new Ping(proto.getNonce(), proto.getLastRoundTripTime(), messageVersion); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/NAES/src/ims/naes/forms/actiondialog/BaseLogic.java
6913
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.naes.forms.actiondialog; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.naes.domain.ActionDialog.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.naes.domain.ActionDialog domain) { setContext(engine, form); this.domain = domain; } protected final void oncmbStatusValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatus().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.naes.vo.lookups.NaesActionStatus existingInstance = (ims.naes.vo.lookups.NaesActionStatus)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusLookup(); return; } } } } else if(value instanceof ims.naes.vo.lookups.NaesActionStatus) { ims.naes.vo.lookups.NaesActionStatus instance = (ims.naes.vo.lookups.NaesActionStatus)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.naes.vo.lookups.NaesActionStatus existingInstance = (ims.naes.vo.lookups.NaesActionStatus)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatus().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusLookup() { this.form.cmbStatus().clear(); ims.naes.vo.lookups.NaesActionStatusCollection lookupCollection = ims.naes.vo.lookups.LookupHelper.getNaesActionStatus(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatus().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusLookupValue(int id) { ims.naes.vo.lookups.NaesActionStatus instance = ims.naes.vo.lookups.LookupHelper.getNaesActionStatusInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatus().setValue(instance); } protected final void defaultcmbStatusLookupValue() { this.form.cmbStatus().setValue((ims.naes.vo.lookups.NaesActionStatus)domain.getLookupService().getDefaultInstance(ims.naes.vo.lookups.NaesActionStatus.class, engine.getFormName().getID(), ims.naes.vo.lookups.NaesActionStatus.TYPE_ID)); } protected final void oncmbActionValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbAction().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.naes.vo.lookups.Action existingInstance = (ims.naes.vo.lookups.Action)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbActionLookup(); return; } } } } else if(value instanceof ims.naes.vo.lookups.Action) { ims.naes.vo.lookups.Action instance = (ims.naes.vo.lookups.Action)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbActionLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.naes.vo.lookups.Action existingInstance = (ims.naes.vo.lookups.Action)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbAction().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbActionLookup() { this.form.cmbAction().clear(); ims.naes.vo.lookups.ActionCollection lookupCollection = ims.naes.vo.lookups.LookupHelper.getAction(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbAction().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbActionLookupValue(int id) { ims.naes.vo.lookups.Action instance = ims.naes.vo.lookups.LookupHelper.getActionInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbAction().setValue(instance); } protected final void defaultcmbActionLookupValue() { this.form.cmbAction().setValue((ims.naes.vo.lookups.Action)domain.getLookupService().getDefaultInstance(ims.naes.vo.lookups.Action.class, engine.getFormName().getID(), ims.naes.vo.lookups.Action.TYPE_ID)); } public final void free() { super.free(); domain = null; } protected ims.naes.domain.ActionDialog domain; }
agpl-3.0
migue/voltdb
tests/bench/throughput/tasks/JavaFib.java
1329
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ class JavaFib { static void doOne() { int a = 0, b = 1; for (int i = 0; i < 20; i++) { int temp = b; b = a + b; a = temp; } } }
agpl-3.0
Fiware/apps.Rss
rss-core/rss-dao/src/main/java/es/upm/fiware/rss/dao/impl/ProductVsObDaoImpl.java
1804
/** * Revenue Settlement and Sharing System GE * Copyright (C) 2011-2014, Javier Lucio - lucio@tid.es * Telefonica Investigacion y Desarrollo, S.A. * * Copyright (C) 2015 CoNWeT Lab., Universidad Politécnica de Madrid * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.upm.fiware.rss.dao.impl; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import es.upm.fiware.rss.dao.ProductVsObDao; import es.upm.fiware.rss.model.BmProductVsOb; import es.upm.fiware.rss.model.BmProductVsObId; /** * */ @Repository public class ProductVsObDaoImpl extends GenericDaoImpl<BmProductVsOb, BmProductVsObId> implements ProductVsObDao { /** * Variable to print the trace. */ private static final Logger LOGGER = LoggerFactory.getLogger(ProductVsObDaoImpl.class); /* * (non-Javadoc) * * @see es.upm.greta.bmms.dao.impl.GenericDaoImpl#getDomainClass() */ @Override protected final Class<BmProductVsOb> getDomainClass() { return BmProductVsOb.class; } }
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/operator/MacroDefinitionOperator.java
4066
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator; import java.util.Iterator; import java.util.List; import com.rapidminer.operator.meta.FeatureIterator; import com.rapidminer.operator.ports.DummyPortPairExtender; import com.rapidminer.operator.ports.PortPairExtender; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeList; import com.rapidminer.parameter.ParameterTypeString; /** * <p> * (Re-)Define macros for the current process. Macros will be replaced in the value strings of parameters by the macro * values defined in the parameter list of this operator. * </p> * * <p> * In the parameter list of this operator, you have to define the macro name (without the enclosing brackets) and the * macro value. The defined macro can then be used in all succeeding operators as parameter value for string type * parameters. A macro must then be enclosed by &quot;MACRO_START&quot; and &quot;MACRO_END&quot;. * </p> * * <p> * There are several predefined macros: * </p> * <ul> * <li>MACRO_STARTprocess_nameMACRO_END: will be replaced by the name of the process (without path and extension)</li> * <li>MACRO_STARTprocess_fileMACRO_END: will be replaced by the file name of the process (with extension)</li> * <li>MACRO_STARTprocess_pathMACRO_END: will be replaced by the complete absolute path of the process file</li> * </ul> * * <p> * In addition to those the user might define arbitrary other macros which will be replaced by arbitrary string during * the process run. Please note also that several other short macros exist, e.g. MACRO_STARTaMACRO_END for the number of * times the current operator was applied. Please refer to the section about macros in the RapidMiner tutorial. Please * note also that other operators like the {@link FeatureIterator} also add specific macros. * </p> * * @author Ingo Mierswa */ public class MacroDefinitionOperator extends Operator { /** The parameter name for &quot;The values of the user defined macros.&quot; */ public static final String PARAMETER_VALUES = "values"; public static final String PARAMETER_MACROS = "macros"; private PortPairExtender dummyPorts = new DummyPortPairExtender("through", getInputPorts(), getOutputPorts()); public MacroDefinitionOperator(OperatorDescription description) { super(description); dummyPorts.start(); getTransformer().addRule(dummyPorts.makePassThroughRule()); } @Override public void doWork() throws OperatorException { List<String[]> macros = getParameterList(PARAMETER_MACROS); Iterator<String[]> i = macros.iterator(); while (i.hasNext()) { String[] macroDefinition = i.next(); String macro = macroDefinition[0]; String value = macroDefinition[1]; getProcess().getMacroHandler().addMacro(macro, value); } dummyPorts.passDataThrough(); } @Override public List<ParameterType> getParameterTypes() { List<ParameterType> types = super.getParameterTypes(); types.add(new ParameterTypeList(PARAMETER_MACROS, "The list of macros defined by the user.", new ParameterTypeString("macro_name", "The macro name."), new ParameterTypeString(PARAMETER_VALUES, "The value of this macro.", false), false)); return types; } }
agpl-3.0
dogjaw2233/tiu-s-mod
build/tmp/recompileMc/sources/net/minecraft/client/resources/data/PackMetadataSection.java
699
package net.minecraft.client.resources.data; import net.minecraft.util.IChatComponent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class PackMetadataSection implements IMetadataSection { private final IChatComponent packDescription; private final int packFormat; public PackMetadataSection(IChatComponent p_i1034_1_, int p_i1034_2_) { this.packDescription = p_i1034_1_; this.packFormat = p_i1034_2_; } public IChatComponent getPackDescription() { return this.packDescription; } public int getPackFormat() { return this.packFormat; } }
lgpl-2.1
julie-sullivan/phytomine
bio/webapp/src/org/intermine/bio/web/displayer/MetabolicGeneSummaryDisplayer.java
15458
package org.intermine.bio.web.displayer; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.intermine.api.InterMineAPI; import org.intermine.api.query.PathQueryExecutor; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStoreException; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.PathQuery; import org.intermine.web.displayer.ReportDisplayer; import org.intermine.web.logic.config.ReportDisplayerConfig; import org.intermine.web.logic.results.ReportObject; import org.intermine.web.logic.session.SessionMethods; /** * * @author radek * */ public class MetabolicGeneSummaryDisplayer extends ReportDisplayer { protected static final Logger LOG = Logger.getLogger(MetabolicGeneSummaryDisplayer.class); /** * Construct with config and the InterMineAPI. * @param config to describe the report displayer * @param im the InterMine API */ public MetabolicGeneSummaryDisplayer(ReportDisplayerConfig config, InterMineAPI im) { super(config, im); } @Override public void display(HttpServletRequest request, ReportObject reportObject) { GeneSummary summary = new GeneSummary(reportObject.getObject(), request); // 1. Pathways count summary.addCollectionCount("Pathways", "Reactome, KEGG", "pathways", "pathways"); // 2. Diseases count summary.addCollectionCount("Diseases", "OMIM", "diseases", "diseases"); // 3. Mouse Alleles count if (summary.isThisAMouser()) { summary.addCollectionCount("Mouse Alleles (MGI)", "mouse alleles", "alleles", "MouseAllelesDisplayer"); } else { summary.addCollectionCount("Mouse Alleles (MGI)", "mouse alleles", allelesPathQuery(summary.getObjectId()), "MouseAllelesDisplayer"); } // 4. GOTerm count summary.addCollectionCount("Gene Ontology", "&nbsp;", goTermPathQuery(summary.getObjectId()), "GeneOntologyDisplayer"); // on sapien pages: if (summary.isThisAHuman()) { // ArrayExpress Gene Expression Tissues & Tissues ArrayList arr = new ArrayList(); arr.add(this.arrayAtlasExpressionTissues(summary)); arr.add(this.arrayAtlasExpressionDiseases(summary)); summary.addCustom("Expression", "Array Express (E-MTAB 62)", arr, "GeneExpressionAtlasTissuesDisplayer", "metabolicGeneSummaryArrayExpressExpressionDisplayer.jsp"); } request.setAttribute("summary", summary); } private Object arrayAtlasExpressionTissues(GeneSummary summary) { PathQuery query = new PathQuery(im.getModel()); query.addViews("Gene.atlasExpression.expression"); query.addOrderBy("Gene.atlasExpression.pValue", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", summary.getObjectId().toString()), "A"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.pValue", "1E-4"), "B"); query.addConstraint(Constraints.eq("Gene.atlasExpression.type", "organism_part"), "D"); query.addConstraint(Constraints.greaterThan("Gene.atlasExpression.tStatistic", "4"), "E"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.tStatistic", "-4"), "F"); query.addConstraint(Constraints.neq("Gene.atlasExpression.condition", "(empty)"), "G"); query.setConstraintLogic("A and B and D and (E or F) and G"); ExportResultsIterator results; try { results = summary.getExecutor().execute(query); } catch (ObjectStoreException e) { throw new RuntimeException(e); } Integer up = 0; Integer down = 0; while (results.hasNext()) { List<ResultElement> item = results.next(); String expression = item.get(0).getField().toString(); if ("UP".equals(expression)) { up += 1; } else { down += 1; } } HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("up", up); map.put("down", down); return map; } private Object arrayAtlasExpressionDiseases(GeneSummary summary) { PathQuery query = new PathQuery(im.getModel()); query.addViews("Gene.atlasExpression.expression"); query.addOrderBy("Gene.atlasExpression.pValue", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", summary.getObjectId().toString()), "A"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.pValue", "1e-4"), "B"); query.addConstraint(Constraints.eq("Gene.atlasExpression.type", "disease_state"), "D"); query.addConstraint(Constraints.greaterThan("Gene.atlasExpression.tStatistic", "4"), "E"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.tStatistic", "-4"), "F"); query.addConstraint(Constraints.neq("Gene.atlasExpression.condition", "(empty)"), "G"); query.setConstraintLogic("A and B and D and (E or F) and G"); ExportResultsIterator results; try { results = summary.getExecutor().execute(query); } catch (ObjectStoreException e) { throw new RuntimeException(e); } Integer up = 0; Integer down = 0; while (results.hasNext()) { List<ResultElement> item = results.next(); String expression = item.get(0).getField().toString(); if ("UP".equals(expression)) { up += 1; } else { down += 1; } } HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("up", up); map.put("down", down); return map; } /** * EMTAB-62 link generator from ebi.ac.uk * @param primaryId * @return * @deprecated because the image is too big */ @SuppressWarnings("unused") @java.lang.Deprecated private String emtabExpression(String primaryId) { if (primaryId != null) { return "http://www.ebi.ac.uk/gxa/webanatomogram/" + primaryId + ".png"; } return null; } /** * Generate PathQuery to Mousey Alleles * @param query * @param objectId * @return */ private PathQuery allelesPathQuery(Integer objectId) { PathQuery query = new PathQuery(im.getModel()); query.addViews("Gene.homologues.homologue.alleles.primaryIdentifier"); query.addConstraint(Constraints.eq("Gene.homologues.homologue.organism.shortName", "M. musculus"), "A"); query.addConstraint(Constraints.eq("Gene.id", objectId.toString()), "B"); query.setConstraintLogic("A and B"); return query; } /** * Generate PathQuery to GOTerms * @param query * @param objectId * @return */ private PathQuery goTermPathQuery(Integer objectId) { PathQuery query = new PathQuery(im.getModel()); query.addViews("Gene.goAnnotation.ontologyTerm.name"); query.addOrderBy("Gene.goAnnotation.ontologyTerm.name", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", objectId.toString())); // parents have to be main ontology, to exclude the root terms query.addConstraint(Constraints.oneOfValues("Gene.goAnnotation.ontologyTerm.parents.name", GeneOntologyDisplayer.ONTOLOGIES)); // not a NOT relationship query.addConstraint(Constraints.isNull("Gene.goAnnotation.qualifier")); return query; } /** * * Internal wrapper. * @author radek * */ public class GeneSummary { private InterMineObject imObj; private PathQueryExecutor executor = null; private LinkedHashMap<String, HashMap<String, Object>> storage; /** * * @param imObj InterMineObject * @param request Request */ public GeneSummary(InterMineObject imObj, HttpServletRequest request) { this.imObj = imObj; storage = new LinkedHashMap<String, HashMap<String, Object>>(); executor = im.getPathQueryExecutor(SessionMethods.getProfile(request.getSession())); } /** * Add a custom object to the displayer. * @param key to show under in the summary * @param description to show under the title * @param data to save on the wrapper object * @param anchor says where we will scroll onlick, an ID attr of the target element * @param jsp to include that knows how to display us */ public void addCustom(String key, String description, Object data, String anchor, String jsp) { storage.put(key, createWrapper("custom", data, anchor, description, jsp)); } /** * Add collection count to the summary. * @param key to show under in the summary * @param description to show under the title * @param param can be a fieldName or a PathQuery * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addCollectionCount(String key, String description, Object param, String anchor) { if (param instanceof PathQuery) { try { storage.put(key, createWrapper("integer", executor.count((PathQuery) param), anchor, description, null)); } catch (ObjectStoreException e) { LOG.error("Problem running PathQuery " + e.toString()); } } else if (param instanceof String) { Collection<?> coll = null; try { coll = (Collection<?>) imObj.getFieldValue(param.toString()); if (coll != null) { storage.put(key, createWrapper("integer", coll.size(), anchor, description, null)); } } catch (IllegalAccessException e) { LOG.error("The field " + param + " does not exist"); } } else { storage.put(key, createWrapper("unknown", param, anchor, description, null)); } } private HashMap<String, Object> createWrapper(String type, Object data, String anchor, String description, String jsp) { HashMap<String, Object> inner = new HashMap<String, Object>(); inner.put("type", type); inner.put("data", data); inner.put("anchor", anchor); inner.put("description", description); if (jsp != null) { inner.put("jsp", jsp); } return inner; } /** * Add collection distinct count to the summary. Will get the distinct value referenced * and get their count. * @param key to show under in the summary * @param description to show under the title * @param param can be a fieldName or a PathQuery * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addCollectionDistinctCount(String key, String description, Object param, String anchor) { if (param instanceof PathQuery) { ExportResultsIterator results; try { results = executor.execute((PathQuery) param); } catch (ObjectStoreException e) { throw new RuntimeException(e); } HashMap<String, Integer> temp = new HashMap<String, Integer>(); while (results.hasNext()) { List<ResultElement> item = results.next(); String value = item.get(0).getField().toString(); if (!temp.keySet().contains(value)) { temp.put(value, 0); } temp.put(value, temp.get(value) + 1); } storage.put(key, createWrapper("map", temp, anchor, description, null)); } else { storage.put(key, createWrapper("unknown", param, anchor, description, null)); } } /** * Add a link to an image for the summary. * @param key to show under in the summary * @param description to show under the title * @param link refers to the src attr of the img element * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addImageLink(String key, String link, String anchor, String description) { storage.put(key, createWrapper("image", link, anchor, description, null)); } /** * * @return InterMineObject ID */ public Integer getObjectId() { return imObj.getId(); } /** * * @return true if we are on a mouseified gene */ public Boolean isThisAMouser() { try { return "Mus".equals(((InterMineObject) imObj.getFieldValue("organism")) .getFieldValue("genus")); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } /** * * @return true if we are on a sapien gene */ public Boolean isThisAHuman() { try { return "Homo".equals(((InterMineObject) imObj.getFieldValue("organism")) .getFieldValue("genus")); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } /** * * @return ReportObject primaryIdentifier */ public String getPrimaryId() { try { return (String) imObj.getFieldValue("primaryIdentifier"); } catch (IllegalAccessException e) { LOG.error("The field primaryIdentifier does not exist"); } return null; } /** * * @return PathQuery Executor */ public PathQueryExecutor getExecutor() { return executor; } /** * * @return Map of the fields configged here for the JSP to traverse */ public LinkedHashMap<String, HashMap<String, Object>> getFields() { return storage; } } }
lgpl-2.1
tavlima/fosstrak-reader
reader-rp-proxy/src/main/java/org/fosstrak/reader/rp/proxy/msg/stubs/serializers/TagFieldSerializer.java
2048
/* * Copyright (C) 2007 ETH Zurich * * This file is part of Fosstrak (www.fosstrak.org). * * Fosstrak is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * Fosstrak 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 Fosstrak; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ package org.fosstrak.reader.rp.proxy.msg.stubs.serializers; /** * TagFieldSerializer objects serialize a command on a TagField into a String * representation. * * @author Andreas Fürer, ETH Zurich Switzerland, Winter 2005/06 * */ public interface TagFieldSerializer { /** * @param name * The name of the tagfield */ public String create(final String name); /** */ public String getName(); /** */ public String getTagFieldName(); /** * @param tagFieldName * The TagFieldName to set */ public String setTagFieldName(final String tagFieldName); /** */ public String getMemoryBank(); /** * @param memoryBank * The memory bank to set */ public String setMemoryBank(final int memoryBank); /** */ public String getOffset(); /** * @param offset * The offset of the data to set */ public String setOffset(final int offset); /** * @return The lenght of the data */ public String getLength(); /** * @param length * The lenght of the data */ public String setLength(final int length); /** * Serializes a TagField command. */ public String serializeCommand(); }
lgpl-2.1
tristantarrant/JGroups
src/org/jgroups/blocks/mux/MuxRpcDispatcher.java
3963
package org.jgroups.blocks.mux; import java.util.Collection; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.MembershipListener; import org.jgroups.Message; import org.jgroups.MessageListener; import org.jgroups.UpHandler; import org.jgroups.blocks.GroupRequest; import org.jgroups.blocks.MethodLookup; import org.jgroups.blocks.RequestCorrelator; import org.jgroups.blocks.RequestHandler; import org.jgroups.blocks.RequestOptions; import org.jgroups.blocks.RpcDispatcher; import org.jgroups.blocks.RspFilter; import org.jgroups.stack.Protocol; /** * A multiplexed message dispatcher. * When used in conjunction with a MuxUpHandler, allows multiple dispatchers to use the same channel. * <br/> * Usage:<br/> * <code> * Channel c = new JChannel(...);<br/> * c.setUpHandler(new MuxUpHandler());<br/> * <br/> * RpcDispatcher d1 = new MuxRpcDispatcher((short) 1, c, ...);<br/> * RpcDispatcher d2 = new MuxRpcDispatcher((short) 2, c, ...);<br/> * <br/> * c.connect(...);<br/> * </code> * @author Bela Ban * @author Paul Ferraro */ public class MuxRpcDispatcher extends RpcDispatcher { private final short scope_id; public MuxRpcDispatcher(short scopeId) { super(); this.scope_id = scopeId; } public MuxRpcDispatcher(short scopeId, Channel channel, MessageListener messageListener, MembershipListener membershipListener, Object serverObject) { this(scopeId); setMessageListener(messageListener); setMembershipListener(membershipListener); setServerObject(serverObject); setChannel(channel); channel.addChannelListener(this); start(); } public MuxRpcDispatcher(short scopeId, Channel channel, MessageListener messageListener, MembershipListener membershipListener, Object serverObject, MethodLookup method_lookup) { this(scopeId); setMethodLookup(method_lookup); setMessageListener(messageListener); setMembershipListener(membershipListener); setServerObject(serverObject); setChannel(channel); channel.addChannelListener(this); start(); } private Muxer<UpHandler> getMuxer() { UpHandler handler = channel.getUpHandler(); return ((handler != null) && (handler instanceof MuxUpHandler)) ? (MuxUpHandler) handler : null; } @Override protected RequestCorrelator createRequestCorrelator(Protocol transport, RequestHandler handler, Address localAddr) { // We can't set the scope of the request correlator here // since this method is called from start() triggered in the // MessageDispatcher constructor, when this.scope is not yet defined return new MuxRequestCorrelator(scope_id, transport, handler, localAddr); } @Override public void start() { super.start(); Muxer<UpHandler> muxer = this.getMuxer(); if (muxer != null) { muxer.add(scope_id, this.getProtocolAdapter()); } } @Override public void stop() { Muxer<UpHandler> muxer = this.getMuxer(); if (muxer != null) { muxer.remove(scope_id); } super.stop(); } /** @Override protected <T> GroupRequest<T> cast(Collection<Address> dests, Message msg, RequestOptions options, boolean blockForResults) throws Exception { RspFilter filter = options.getRspFilter(); return super.cast(dests, msg, options.setRspFilter((filter != null) ? new NoMuxHandlerRspFilter(filter) : new NoMuxHandlerRspFilter()), blockForResults); }*/ @Override protected <T> GroupRequest <T> cast(Collection<Address> dests, Message msg, RequestOptions options, boolean blockForResults) throws Exception { RspFilter filter = options.getRspFilter(); return super.cast(dests, msg, options.setRspFilter(NoMuxHandlerRspFilter.createInstance(filter)), blockForResults); } }
lgpl-2.1
xwiki-labs/sankoreorg
xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/cache/api/XWikiCacheService.java
2381
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.cache.api; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiException; import java.util.Properties; @Deprecated public interface XWikiCacheService { /** * Initializes the service */ public void init(XWiki context); /* * Returns a local only (never clustered) cache */ public XWikiCache newLocalCache() throws XWikiException; /* * Returns a local only (never clustered) cache with given capacity */ public XWikiCache newLocalCache(int capacity) throws XWikiException; /* * Returns a cache that could be configured to be clustered */ public XWikiCache newCache(String cacheName) throws XWikiException; /* * Returns a cache that could be configured to be clustered with the given capacity */ public XWikiCache newCache(String cacheName, int capacity) throws XWikiException; /* * Returns a custom cache */ public XWikiCache newCache(String cacheName, Properties props) throws XWikiException; /* * Returns a custom local cache */ public XWikiCache newLocalCache(Properties props) throws XWikiException; /* * Returns a custom cache with capacity */ public XWikiCache newCache(String cacheName, Properties props, int capacity) throws XWikiException; /* * Returns a custom local cache with capacity */ public XWikiCache newLocalCache(Properties props, int capacity) throws XWikiException; }
lgpl-2.1
SuperUnitato/UnLonely
build/tmp/recompileMc/sources/net/minecraft/client/renderer/entity/RenderBat.java
1645
package net.minecraft.client.renderer.entity; import net.minecraft.client.model.ModelBat; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.passive.EntityBat; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderBat extends RenderLiving<EntityBat> { private static final ResourceLocation BAT_TEXTURES = new ResourceLocation("textures/entity/bat.png"); public RenderBat(RenderManager renderManagerIn) { super(renderManagerIn, new ModelBat(), 0.25F); } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityBat entity) { return BAT_TEXTURES; } /** * Allows the render to do state modifications necessary before the model is rendered. */ protected void preRenderCallback(EntityBat entitylivingbaseIn, float partialTickTime) { GlStateManager.scale(0.35F, 0.35F, 0.35F); } protected void applyRotations(EntityBat entityLiving, float p_77043_2_, float p_77043_3_, float partialTicks) { if (entityLiving.getIsBatHanging()) { GlStateManager.translate(0.0F, -0.1F, 0.0F); } else { GlStateManager.translate(0.0F, MathHelper.cos(p_77043_2_ * 0.3F) * 0.1F, 0.0F); } super.applyRotations(entityLiving, p_77043_2_, p_77043_3_, partialTicks); } }
lgpl-2.1
hohonuuli/vars
vars-annotation/src/main/java/vars/annotation/ui/commandqueue/CommandEvent.java
1053
package vars.annotation.ui.commandqueue; /** * EventBus Event class. Wraps a command that will be stored in the CommandQueue. It * has a direction, DO or UNDO. In general, only DO commands should be used by developers. * @author Brian Schlining * @since 2011-09-21 */ public class CommandEvent { public static enum DoOrUndo { DO, UNDO; public DoOrUndo inverse() { return (this == DO) ? UNDO : DO; } } private final Command command; private final DoOrUndo doOrUndo; public CommandEvent(Command command) { this(command, DoOrUndo.DO); } public CommandEvent(Command command, DoOrUndo doOrUndo) { if (command == null || doOrUndo == null) { throw new IllegalArgumentException("null arguments are NOT allowed in the constructor"); } this.command = command; this.doOrUndo = doOrUndo; } public Command getCommand() { return command; } public DoOrUndo getDoOrUndo() { return doOrUndo; } }
lgpl-2.1
trixmot/mod1
build/tmp/recompileMc/sources/net/minecraftforge/fml/common/ModMetadata.java
2256
/* * Forge Mod Loader * Copyright (c) 2012-2013 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * cpw - implementation */ package net.minecraftforge.fml.common; import java.util.List; import java.util.Set; import net.minecraftforge.fml.common.functions.ModNameFunction; import net.minecraftforge.fml.common.versioning.ArtifactVersion; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.annotations.SerializedName; /** * @author cpw * */ public class ModMetadata { @SerializedName("modid") public String modId; public String name; public String description = ""; public String url = ""; public String updateUrl = ""; public String logoFile = ""; public String version = ""; public List<String> authorList = Lists.newArrayList(); public String credits = ""; public String parent = ""; public String[] screenshots; // this field is not for use in the json public transient ModContainer parentMod; // this field is not for use in the json public transient List<ModContainer> childMods = Lists.newArrayList(); public boolean useDependencyInformation; public Set<ArtifactVersion> requiredMods = Sets.newHashSet(); public List<ArtifactVersion> dependencies = Lists.newArrayList(); public List<ArtifactVersion> dependants = Lists.newArrayList(); // this field is not for use in the json public transient boolean autogenerated; public ModMetadata() { } public String getChildModCountString() { return String.format("%d child mod%s", childMods.size(), childMods.size() != 1 ? "s" : ""); } public String getAuthorList() { return Joiner.on(", ").join(authorList); } public String getChildModList() { return Joiner.on(", ").join(Lists.transform(childMods, new ModNameFunction())); } public String printableSortingRules() { return ""; } }
lgpl-2.1
ryanrhymes/mobiccnx
javasrc/src/org/ccnx/ccn/profiles/SegmentationProfile.java
22097
/* * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009, 2010, 2012 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.profiles; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.impl.support.DataUtils; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Exclude; import org.ccnx.ccn.protocol.ExcludeAny; import org.ccnx.ccn.protocol.ExcludeComponent; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; /** * We speak in terms of segments, not fragments, as this profile * also encompasses packet-oriented data with sequenced segments rather * than block data divided into fragments. * Sequence/segment numbers occupy the final component of the CCN name * (again, not counting the digest component). For consecutive numbering, * the first byte of the sequence component is 0x00. The remaining bytes * hold the sequence number in big-endian unsigned binary, using the minimum number * of bytes. Thus sequence number 0 is encoded in just one byte, %00, and * sequence number 1 is %00%01. Note that this encoding is not quite * dense - %00%00 is unused, as are other components that start with * these two bytes. * For non-consecutive numbering (e.g, using byte offsets) the value * 0xFB may be used as a marker. * * */ public class SegmentationProfile implements CCNProfile { /** * Is it fragmented, and what is its fragment number? */ public static final long BASE_SEGMENT = 0; public static final byte SEGMENT_MARKER = (byte)0x00; public static final byte NO_SEGMENT_POSTFIX = 0x00; public static final byte [] FIRST_SEGMENT_MARKER = new byte[]{SEGMENT_MARKER}; public static final byte [] NO_SEGMENT_MARKER = new byte[]{SEGMENT_MARKER, NO_SEGMENT_POSTFIX}; /** * What does its fragment number mean? */ public enum SegmentNumberType {SEGMENT_FIXED_INCREMENT, SEGMENT_BYTE_COUNT} /** * Default blocksize. This must be a multiple of the block size of standard * encryption algorithms (generally, 128 bits = 16 bytes; conservatively * 256 bits = 32 bytes, really conservatively, support 192 bits = 24 bytes; * so 32 bytes with unused bytes in the 192-bit case (otherwise we'd have * to use the LCM, 96 bytes, which is really inefficient). */ public static final int DEFAULT_BLOCKSIZE = 4096; public static final int DEFAULT_INCREMENT = 1; public static final int DEFAULT_SCALE = 1; /** * The library will attempt to get the last segment, without knowing exactly what * segment number this will be. Additionally, it is possible for a streaming producer to * continuously push a new segment and never have an end. The MAX_LAST_SEGMENT_LOOP_ATTEMPT * variable avoids blocking forever in this case. The getLastSegment function will * attempt x times (default is 10), before handing back the current content object, which is a * best effort attempt at the last segment. */ public static final int MAX_LAST_SEGMENT_LOOP_ATTEMPTS = 10; /** * Control whether fragments start at 0 or 1. * @return */ public static final long baseSegment() { return BASE_SEGMENT; } public static boolean isUnsegmented(ContentName name) { return isNotSegmentMarker(name.lastComponent()); } public static boolean isNotSegmentMarker(byte [] potentialSegmentID) { return ((null == potentialSegmentID) || (0 == potentialSegmentID.length) || (SEGMENT_MARKER != potentialSegmentID[0]) || ((potentialSegmentID.length > 1) && (NO_SEGMENT_POSTFIX == potentialSegmentID[1]))); } public final static boolean isSegmentMarker(byte [] potentialSegmentID) { return (!isNotSegmentMarker(potentialSegmentID)); } public static boolean isSegment(ContentName name) { if (null == name) return false; return (!isUnsegmented(name)); } public static ContentName segmentRoot(ContentName name) { if (isUnsegmented(name)) return name; return name.parent(); } public static ContentName segmentName(ContentName name, long index) { // Need a minimum-bytes big-endian representation of i. ContentName baseName = name; if (isSegment(name)) { baseName = segmentRoot(name); } return new ContentName(baseName, getSegmentNumberNameComponent(index)); } public static byte [] getSegmentNumberNameComponent(long segmentNumber) { byte [] segmentNumberNameComponent = null; if (baseSegment() == segmentNumber) { segmentNumberNameComponent = FIRST_SEGMENT_MARKER; } else { segmentNumberNameComponent = DataUtils.unsignedLongToByteArray(segmentNumber, SEGMENT_MARKER); } return segmentNumberNameComponent; } public static long getSegmentNumber(byte [] segmentNumberNameComponent) { if (isSegmentMarker(segmentNumberNameComponent)) { // Will behave properly with everything but first fragment of fragmented content. if (segmentNumberNameComponent.length == 1) return 0; return DataUtils.byteArrayToUnsignedLong(segmentNumberNameComponent, 1); } // If this isn't formatted as one of our segment numbers, suspect it might // be a sequence (e.g. a packet stream), and attempt to read the last name // component as a number. return DataUtils.byteArrayToUnsignedLong(segmentNumberNameComponent); } /** * Extract the segment information from this name. Try to return any valid * number encoded in the last name component, be it either a raw big-endian * encoding of a number, or more likely, a properly-formatted segment * number with segment marker. * @throws NumberFormatException if neither number type found in last name component */ public static long getSegmentNumber(ContentName name) { return getSegmentNumber(name.lastComponent()); } /** * Just confirms that last name component is a segment, and that its segment number is baseSegment() (0). * @param name * @return */ public static boolean isFirstSegment(ContentName name) { if (!isSegment(name)) return false; return (getSegmentNumber(name) == BASE_SEGMENT); } /** * Retrieves a specific segment, following the above naming conventions. * If necessary (not currently), will issue repeated requests until it gets a segment * that matches requirements and verifies, or it times out. If it * can't find anything, should return null. * TODO Eventually cope if verification fails (exclude, warn and retry). * @param desiredContent * @param segmentNumber If null, gets baseSegment(). * @param timeout * @param verifier Cannot be null. * @param handle * @return the segment it got, or null if nothing matching could be found in the * allotted time * @throws IOException only on error */ public static ContentObject getSegment(ContentName desiredContent, Long desiredSegmentNumber, PublisherPublicKeyDigest publisher, long timeout, ContentVerifier verifier, CCNHandle handle) throws IOException { // Block name requested should be interpreted literally, not taken // relative to baseSegment(). if (null == desiredSegmentNumber) { desiredSegmentNumber = baseSegment(); } ContentName segmentName = segmentName(desiredContent, desiredSegmentNumber); // TODO use better exclude filters to ensure we're only getting segments. if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info("getSegment: getting segment {0}", segmentName); ContentObject segment = handle.get(Interest.lower(segmentName, 1, publisher), timeout); if (null == segment) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Cannot get segment {0} of file {1} expected segment: {2}.", desiredSegmentNumber, desiredContent, segmentName); return null; // used to throw IOException, which was wrong. Do we want to be more aggressive? } else { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "getsegment: retrieved segment {0}.", segment.name()); } if (null == verifier) { verifier = ContentObject.SimpleVerifier.getDefaultVerifier(); } // So for the segment, we assume we have a potential document. if (!verifier.verify(segment)) { // TODO eventually try to go and look for another option if (Log.isLoggable(Log.FAC_IO, Level.INFO)) Log.info(Log.FAC_IO, "Retrieved segment {0}, but it didn't verify.", segment.name()); return null; } return segment; } /** * Creates an Interest for a specified segment number. If the supplied name already * ends with a segment number, the interest will have the supplied segment in the name * instead. * * @param name ContentName for the desired ContentObject * @param segmentNumber segment number to append to the name, if null, uses the baseSegment number * @param publisher can be null * * @return interest **/ public static Interest segmentInterest(ContentName name, Long segmentNumber, PublisherPublicKeyDigest publisher){ ContentName interestName = null; //make sure the desired segment number is specified if (null == segmentNumber) { segmentNumber = baseSegment(); } //check if the name already has a segment in the last spot if (isSegment(name)) { //this already has a segment, trim it off interestName = segmentRoot(name); } else { interestName = name; } interestName = segmentName(interestName, segmentNumber); if (Log.isLoggable(Log.FAC_IO, Level.FINE)) Log.fine(Log.FAC_IO, "segmentInterest: creating interest for {0} from ContentName {1} and segmentNumber {2}", interestName, name, segmentNumber); Interest interest = Interest.lower(interestName, 1, publisher); return interest; } /** * Creates an Interest that allows for only a segment number and an ephemeral digest below the * given prefix. * @param prefix * @param publisher * @return */ public static Interest anySegmentInterest(ContentName prefix, PublisherPublicKeyDigest publisher) { Interest theInterest = Interest.lower(prefix, 2, publisher); // theInterest.exclude(acceptSegments()) return theInterest; } /** * Creates an Interest for the first segment. * * @param name ContentName for the desired ContentObject * @param publisher can be null * * @return interest **/ public static Interest firstSegmentInterest(ContentName name, PublisherPublicKeyDigest publisher){ return segmentInterest(name, baseSegment(), publisher); } public static Interest nextSegmentInterest(ContentName name, PublisherPublicKeyDigest publisher) { Interest interest = null; ContentName interestName = null; if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "nextSegmentInterest: creating interest for {0} from ContentName {1}", interestName, name); //TODO need to make sure we only get segments back and not other things like versions interest = Interest.next(interestName, null, null, 2, 2, publisher); return interest; } /** * Creates an Interest to find the right-most child from the given segment number * or the base segment if one is not supplied. This attempts to find the last segment for * the given content name. Due to caching, this does not guarantee the interest will find the * last segment, higher layer code must verify that the ContentObject returned for this interest * is the last one. * * TODO: depends on acceptSegments being fully implemented. right now mainly depends on the number of component restriction. * * @param name ContentName for the prefix of the Interest * @param segmentNumber create an interest for the last segment number after this number * @param publisher can be null * @return interest */ public static Interest lastSegmentInterest(ContentName name, Long segmentNumber, PublisherPublicKeyDigest publisher){ Interest interest = null; ContentName interestName = null; //see if a segment number was supplied if (segmentNumber == null) { segmentNumber = baseSegment(); } //check if the name has a segment number if (isSegment(name)) { //this already has a segment //is this segment before or after the segmentNumber if (segmentNumber < getSegmentNumber(name)) { //the segment number in the name is higher... use this interestName = name; } else { //the segment number provided is bigger... use that interestName = segmentName(name, segmentNumber); } } else { interestName = segmentName(name, segmentNumber); } if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "lastSegmentInterest: creating interest for {0} from ContentName {1} and segmentNumber {2}", interestName, name, segmentNumber); //TODO need to make sure we only get segments back and not other things like versions interest = Interest.last(interestName, acceptSegments(getSegmentNumberNameComponent(segmentNumber)), null, 2, 2, publisher); return interest; } /** * Creates an Interest to find the right-most child from the given segment number * or the base segment if one is not supplied. This Interest will attempt to find the last segment for * the given content name. Due to caching, this does not guarantee the interest will find the * last segment, higher layer code must verify that the ContentObject returned for this interest * is the last one. * * @param name ContentName for the prefix of the Interest * @param publisher can be null * @return interest */ public static Interest lastSegmentInterest(ContentName name, PublisherPublicKeyDigest publisher){ return lastSegmentInterest(name, baseSegment(), publisher); } /** * This method returns the last segment for the name provided. If there are no segments for the supplied name, * the method will return null. It is possible for producers to continuously make new segments. In this case, * the function returns last content object it finds (and verifies) after some number of attempts (the default * value is 10 for now). The function can be called with a starting segment, the method will attempt to * find the last segment after the provided segment number. This method assumes either the last component of * the supplied name is a segment or the next component of the name will be a segment. It does not attempt to * resolve the remainder of the prefix (for example, it will not attempt to distinguish which version to use). * * If the method is called with a segment in the name and as an additional parameter, the method will use the higher * number to locate the last segment. Again, if no segment is found, the method will return null. * * Calling functions should explicitly check if the returned segment is the best-effort at the last segment, or * the marked last segment (if it matters to the caller). * * @param name * @param publisher * @param timeout * @param verifier * @param handle * @return * @throws IOException */ public static ContentObject getLastSegment(ContentName name, PublisherPublicKeyDigest publisher, long timeout, ContentVerifier verifier, CCNHandle handle) throws IOException{ ContentName segmentName = null; ContentObject co = null; Interest getLastInterest = null; int attempts = MAX_LAST_SEGMENT_LOOP_ATTEMPTS; //want to start with a name with a segment number in it if(isSegment(name)){ //the name already has a segment... could this be the segment we want? segmentName = name; getLastInterest = lastSegmentInterest(segmentName, publisher); } else { //this doesn't have a segment already //the last segment could be the first one... segmentName = segmentName(name, baseSegment()); getLastInterest = firstSegmentInterest(segmentName, publisher); } while (true) { attempts--; co = handle.get(getLastInterest, timeout); if (co == null) { if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "Null returned from getLastSegment for name: {0}",name); return null; } else { if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "returned contentObject: {0}",co.fullName()); } //now we should have a content object after the segment in the name we started with, but is it the last one? if (isSegment(co.name())) { //double check that we have a segmented name //we have a later segment, but is it the last one? //check the final segment marker or if we are on our last attempt if (isLastSegment(co) || attempts == 0) { //this is the last segment (or last attempt)... check if it verifies. if (verifier.verify(co)) { return co; } else { //this did not verify... need to determine how to handle this if (Log.isLoggable(Log.FAC_IO, Level.WARNING)) Log.warning(Log.FAC_IO, "VERIFICATION FAILURE: " + co.name() + ", need to find better way to decide what to do next."); } } else { //this was not the last segment.. use the co.name() to try again. segmentName = co.name().cut(getLastInterest.name().count()); getLastInterest = lastSegmentInterest(segmentName, getSegmentNumber(co.name()), publisher); if (Log.isLoggable(Log.FAC_IO, Level.FINE)) Log.fine(Log.FAC_IO, "an object was returned... but not the last segment, next Interest: {0}",getLastInterest); } } else { if (Log.isLoggable(Log.FAC_IO, Level.WARNING)) Log.warning(Log.FAC_IO, "SegmentationProfile.getLastSegment: had a content object returned that did not have a segment in the last component Interest = {0} ContentObject = {1}", segmentName, co.name()); return null; } } } public static boolean isLastSegment(ContentObject co) { if (isSegment(co.name())) { //we have a segment to check... if(!co.signedInfo().emptyFinalBlockID()) { //the final block id is set if(getSegmentNumber(co.name()) == getSegmentNumber(co.signedInfo().getFinalBlockID())) return true; } } return false; } /** * Builds an Exclude filter that excludes components that are not segments in the next component. * @param startingSegmentComponent The latest segment component we know about. Can be null or * the SegmentationProfile.baseSegment() component to indicate that we want to start * from 0 (we don't have a known segment to start from). This exclude filter will * find segments *after* the segment represented in startingSegmentComponent. * @return An exclude filter. * * TODO needs to be fully implemented */ public static Exclude acceptSegments(byte [] startingSegmentComponent) { byte [] start = null; // initially exclude name components just before the first segment, whether that is the // 0th segment or the segment passed in if ((null == startingSegmentComponent) || (SegmentationProfile.getSegmentNumber(startingSegmentComponent) == baseSegment())) { start = SegmentationProfile.FIRST_SEGMENT_MARKER; } else { start = startingSegmentComponent; } ArrayList<Exclude.Element> ees = new ArrayList<Exclude.Element>(); ees.add(new ExcludeAny()); ees.add(new ExcludeComponent(start)); //ees.add(new ExcludeComponent(new byte [] { SEGMENT_MARKER+1} )); //ees.add(new ExcludeAny()); return new Exclude(ees); } /** * Function to get the next segment after segment in the supplied name (or the first segment if no segment is given). * */ public static ContentObject getNextSegment(ContentName name, PublisherPublicKeyDigest publisher, long timeout, ContentVerifier verifier, CCNHandle handle) throws IOException { ContentName segmentName = null; ContentObject co = null; Interest getNextInterest = null; long segmentNumber = -1; //want to start with a name with a segment number in it if(isSegment(name)){ //the name already has a segment... could this be the segment we want? segmentName = name; segmentNumber = getSegmentNumber(name); getNextInterest = segmentInterest(segmentName, segmentNumber+1, publisher); //getNextInterest = nextSegmentInterest(segmentName, publisher); } else { //this doesn't have a segment already //the last segment could be the first one... segmentName = segmentName(name, baseSegment()); getNextInterest = firstSegmentInterest(segmentName, publisher); } co = handle.get(getNextInterest, timeout); if (co == null) { if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "Null returned from getNextSegment for name: {0}",name); return null; } else { if (Log.isLoggable(Log.FAC_IO, Level.FINER)) Log.finer(Log.FAC_IO, "returned contentObject: {0}",co.fullName()); } //now we should have a content object after the segment in the name we started with, but is it the last one? if (isSegment(co.name())) { //double check that we have a segmented name //we have a later segment, but is it the next one? //check the final segment marker or if we are on our last attempt if (segmentNumber+1 == getSegmentNumber(co.name())) { //this is the next segment (or last attempt)... check if it verifies. if (verifier.verify(co)) { return co; } else { //this did not verify... need to determine how to handle this Log.warning(Log.FAC_IO, "VERIFICATION FAILURE: " + co.name() + ", need to find better way to decide what to do next."); } } } //we didn't get back the segment number we were expecting... needs to be more robust return null; } }
lgpl-2.1
trixmot/mod1
build/tmp/recompileMc/sources/net/minecraft/network/play/server/S41PacketServerDifficulty.java
1831
package net.minecraft.network.play.server; import java.io.IOException; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.EnumDifficulty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class S41PacketServerDifficulty implements Packet { private EnumDifficulty field_179833_a; private boolean field_179832_b; private static final String __OBFID = "CL_00002303"; public S41PacketServerDifficulty() {} public S41PacketServerDifficulty(EnumDifficulty p_i45987_1_, boolean p_i45987_2_) { this.field_179833_a = p_i45987_1_; this.field_179832_b = p_i45987_2_; } public void func_179829_a(INetHandlerPlayClient p_179829_1_) { p_179829_1_.handleServerDifficulty(this); } /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer buf) throws IOException { this.field_179833_a = EnumDifficulty.getDifficultyEnum(buf.readUnsignedByte()); } /** * Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer buf) throws IOException { buf.writeByte(this.field_179833_a.getDifficultyId()); } @SideOnly(Side.CLIENT) public boolean func_179830_a() { return this.field_179832_b; } /** * Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandler handler) { this.func_179829_a((INetHandlerPlayClient)handler); } @SideOnly(Side.CLIENT) public EnumDifficulty func_179831_b() { return this.field_179833_a; } }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/annotations/Persister.java
686
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Specify a custom persister. * * @author Shawn Clowater */ @java.lang.annotation.Target( { ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Persister { /** * The custom persister class. */ Class<?> impl(); }
lgpl-2.1
EdwardNewK/libbluray
src/libbluray/bdj/java/org/videolan/BDJLoader.java
11234
/* * This file is part of libbluray * Copyright (C) 2010 William Hahne * * 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, see * <http://www.gnu.org/licenses/>. */ package org.videolan; import java.io.File; import java.io.InputStream; import java.io.InvalidObjectException; import java.util.Enumeration; import org.videolan.Logger; import org.bluray.net.BDLocator; import org.bluray.ti.TitleImpl; import org.davic.media.MediaLocator; import org.dvb.application.AppID; import org.dvb.application.AppsDatabase; import org.dvb.application.CurrentServiceFilter; import javax.media.Manager; import javax.tv.locator.Locator; import org.videolan.bdjo.AppEntry; import org.videolan.bdjo.Bdjo; import org.videolan.bdjo.GraphicsResolution; import org.videolan.bdjo.PlayListTable; import org.videolan.bdjo.TerminalInfo; import org.videolan.media.content.PlayerManager; public class BDJLoader { /* called by org.dvb.ui.FontFactory */ public static File addFont(InputStream is) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.addFont(is); } return null; } /* called by org.dvb.ui.FontFactory */ public static File addFont(String fontFile) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.addFont(fontFile); } return null; } /* called by BDJSecurityManager */ protected static void accessFile(String file) { VFSCache localCache = vfsCache; if (localCache != null) { localCache.accessFile(file); } } public static String getCachedFile(String path) { VFSCache localCache = vfsCache; if (localCache != null) { return localCache.map(path); } return path; } public static boolean load(TitleImpl title, boolean restart, BDJLoaderCallback callback) { // This method should be called only from ServiceContextFactory if (title == null) return false; synchronized (BDJLoader.class) { if (queue == null) queue = new BDJActionQueue(null, "BDJLoader"); } queue.put(new BDJLoaderAction(title, restart, callback)); return true; } public static boolean unload(BDJLoaderCallback callback) { // This method should be called only from ServiceContextFactory synchronized (BDJLoader.class) { if (queue == null) queue = new BDJActionQueue(null, "BDJLoader"); } queue.put(new BDJLoaderAction(null, false, callback)); return true; } protected static void shutdown() { try { if (queue != null) { queue.shutdown(); } } catch (Throwable e) { logger.error("shutdown() failed: " + e + "\n" + Logger.dumpStack(e)); } queue = null; vfsCache = null; } private static boolean loadN(TitleImpl title, boolean restart) { if (vfsCache == null) { vfsCache = VFSCache.createInstance(); } TitleInfo ti = title.getTitleInfo(); if (!ti.isBdj()) { logger.info("Not BD-J title - requesting HDMV title start"); unloadN(); return Libbluray.selectHdmvTitle(title.getTitleNum()); } try { // load bdjo Bdjo bdjo = Libbluray.getBdjo(ti.getBdjoName()); if (bdjo == null) throw new InvalidObjectException("bdjo not loaded"); AppEntry[] appTable = bdjo.getAppTable(); // initialize AppCaches if (vfsCache != null) { vfsCache.add(bdjo.getAppCaches()); } // reuse appProxys BDJAppProxy[] proxys = new BDJAppProxy[appTable.length]; AppsDatabase db = AppsDatabase.getAppsDatabase(); Enumeration ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); AppEntry entry = (AppEntry)db.getAppAttributes(id); for (int i = 0; i < appTable.length; i++) { if (id.equals(appTable[i].getIdentifier()) && entry.getInitialClass().equals(appTable[i].getInitialClass())) { if (restart && appTable[i].getIsServiceBound()) { logger.info("Stopping xlet " + appTable[i].getInitialClass() + " (for restart)"); proxy.stop(true); } else { logger.info("Keeping xlet " + appTable[i].getInitialClass()); proxy.getXletContext().update(appTable[i], bdjo.getAppCaches()); proxys[i] = proxy; proxy = null; } break; } } if (proxy != null) { logger.info("Terminating xlet " + (entry == null ? "?" : entry.getInitialClass())); proxy.release(); } } // start bdj window GUIManager gui = GUIManager.createInstance(); TerminalInfo terminfo = bdjo.getTerminalInfo(); GraphicsResolution res = terminfo.getResolution(); gui.setDefaultFont(terminfo.getDefaultFont()); gui.setResizable(true); gui.setSize(res.getWidth(), res.getHeight()); gui.setVisible(true); Libbluray.setUOMask(terminfo.getMenuCallMask(), terminfo.getTitleSearchMask()); Libbluray.setKeyInterest(bdjo.getKeyInterestTable()); // initialize appProxys for (int i = 0; i < appTable.length; i++) { if (proxys[i] == null) { proxys[i] = BDJAppProxy.newInstance( new BDJXletContext( appTable[i], bdjo.getAppCaches(), gui)); /* log startup class, startup parameters and jar file */ String[] params = appTable[i].getParams(); String p = ""; if (params != null && params.length > 0) { p = "(" + StrUtil.Join(params, ",") + ")"; } logger.info("Loaded class: " + appTable[i].getInitialClass() + p + " from " + appTable[i].getBasePath() + ".jar"); } else { logger.info("Reused class: " + appTable[i].getInitialClass() + " from " + appTable[i].getBasePath() + ".jar"); } } // change psr Libbluray.writePSR(Libbluray.PSR_TITLE_NUMBER, title.getTitleNum()); // notify AppsDatabase ((BDJAppsDatabase)BDJAppsDatabase.getAppsDatabase()).newDatabase(bdjo, proxys); // now run all the xlets for (int i = 0; i < appTable.length; i++) { int code = appTable[i].getControlCode(); if (code == AppEntry.AUTOSTART) { logger.info("Autostart xlet " + i + ": " + appTable[i].getInitialClass()); proxys[i].start(); } else if (code == AppEntry.PRESENT) { logger.info("Init xlet " + i + ": " + appTable[i].getInitialClass()); proxys[i].init(); } else { logger.info("Unsupported xlet code (" +code+") xlet " + i + ": " + appTable[i].getInitialClass()); } } logger.info("Finished initializing and starting xlets."); // auto start playlist PlayListTable plt = bdjo.getAccessiblePlaylists(); if ((plt != null) && (plt.isAutostartFirst())) { logger.info("Auto-starting playlist"); String[] pl = plt.getPlayLists(); if (pl.length > 0) Manager.createPlayer(new MediaLocator(new BDLocator("bd://PLAYLIST:" + pl[0]))).start(); } return true; } catch (Throwable e) { logger.error("loadN() failed: " + e + "\n" + Logger.dumpStack(e)); unloadN(); return false; } } private static boolean unloadN() { try { try { GUIManager.getInstance().setVisible(false); } catch (Error e) { } AppsDatabase db = AppsDatabase.getAppsDatabase(); /* stop xlets first */ Enumeration ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); proxy.stop(true); } ids = db.getAppIDs(new CurrentServiceFilter()); while (ids.hasMoreElements()) { AppID id = (AppID)ids.nextElement(); BDJAppProxy proxy = (BDJAppProxy)db.getAppProxy(id); proxy.release(); } ((BDJAppsDatabase)db).newDatabase(null, null); PlayerManager.getInstance().releaseAllPlayers(true); return true; } catch (Throwable e) { logger.error("unloadN() failed: " + e + "\n" + Logger.dumpStack(e)); return false; } } private static class BDJLoaderAction extends BDJAction { public BDJLoaderAction(TitleImpl title, boolean restart, BDJLoaderCallback callback) { this.title = title; this.restart = restart; this.callback = callback; } protected void doAction() { boolean succeed; if (title != null) succeed = loadN(title, restart); else succeed = unloadN(); if (callback != null) callback.loaderDone(succeed); } private TitleImpl title; private boolean restart; private BDJLoaderCallback callback; } private static final Logger logger = Logger.getLogger(BDJLoader.class.getName()); private static BDJActionQueue queue = null; private static VFSCache vfsCache = null; }
lgpl-2.1
ChristophBroeker/betsy
src/test/groovy/peal/helper/ZipFileHelperTest.java
732
package peal.helper; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ZipFileHelperTest { private static final Path TEST_BPEL_SEQUENCE = Paths.get("src/test/resources/Sequence/Sequence.bpel"); @Test public void findBpelProcessName() throws Exception { assertEquals("Sequence", ZipFileHelper.findBpelProcessName(Paths.get("src/test/resources/Sequence/Sequence.bpel"))); } @Test public void findBpelProcessNamespace() throws Exception { assertEquals("http://dsg.wiai.uniba.de/betsy/activities/bpel/sequence", ZipFileHelper.findBpelTargetNameSpaceInPath(TEST_BPEL_SEQUENCE)); } }
lgpl-3.0
dukeboard/kevoree-modeling-framework
org.kevoree.modeling.microframework/src/test/java/org/kevoree/modeling/memory/struct/map/impl/ArrayLongHashMapTest.java
463
package org.kevoree.modeling.memory.struct.map.impl; import org.kevoree.modeling.memory.struct.map.BaseKLongHashMapTest; import org.kevoree.modeling.memory.struct.map.KLongMap; /** * Created by duke on 03/03/15. */ public class ArrayLongHashMapTest extends BaseKLongHashMapTest { @Override public KLongMap createKLongHashMap(int p_initalCapacity, float p_loadFactor) { return new ArrayLongMap<String>(p_initalCapacity, p_loadFactor); } }
lgpl-3.0
JKatzwinkel/bts
org.bbaw.bts.ui.corpus/src/org/bbaw/bts/ui/corpus/handlers/PassportOpenObjectMetadataHandler.java
1240
package org.bbaw.bts.ui.corpus.handlers; import javax.inject.Named; import org.bbaw.bts.btsmodel.BTSObject; import org.bbaw.bts.core.commons.BTSCoreConstants; import org.bbaw.bts.core.corpus.controller.partController.CorpusNavigatorController; import org.bbaw.bts.ui.corpus.dialogs.PassportEditorDialog; import org.eclipse.e4.core.contexts.ContextInjectionFactory; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.swt.widgets.Shell; public class PassportOpenObjectMetadataHandler { @Execute public void execute(IEclipseContext context, @Named("objectId") String objectId, CorpusNavigatorController corpusNavigatorController) { if (objectId != null) { BTSObject object = corpusNavigatorController.find(objectId, null); if (object == null) return; IEclipseContext child = context.createChild(); child.set(BTSObject.class, object); child.set(Shell.class, new Shell()); child.set(BTSCoreConstants.CORE_EXPRESSION_MAY_EDIT, false); PassportEditorDialog dialog = ContextInjectionFactory.make( PassportEditorDialog.class, child); if (dialog.open() == dialog.OK) { } } } }
lgpl-3.0
rpau/walkmod-core
src/test/resources/multimodulewithoutconfig/module1/src/main/java/Bar.java
22
public class Bar { }
lgpl-3.0
haisamido/SFDaaS
src/org/apache/commons/math/geometry/NotARotationMatrixException.java
2171
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.geometry; import org.apache.commons.math.MathException; import org.apache.commons.math.exception.util.Localizable; /** * This class represents exceptions thrown while building rotations * from matrices. * * @version $Revision: 983921 $ $Date: 2010-08-10 12:46:06 +0200 (mar. 10 août 2010) $ * @since 1.2 */ public class NotARotationMatrixException extends MathException { /** Serializable version identifier */ private static final long serialVersionUID = 5647178478658937642L; /** * Simple constructor. * Build an exception by translating and formating a message * @param specifier format specifier (to be translated) * @param parts to insert in the format (no translation) * @deprecated as of 2.2 replaced by {@link #NotARotationMatrixException(Localizable, Object...)} */ @Deprecated public NotARotationMatrixException(String specifier, Object ... parts) { super(specifier, parts); } /** * Simple constructor. * Build an exception by translating and formating a message * @param specifier format specifier (to be translated) * @param parts to insert in the format (no translation) * @since 2.2 */ public NotARotationMatrixException(Localizable specifier, Object ... parts) { super(specifier, parts); } }
lgpl-3.0
delphiprogramming/gisgraphy
src/main/java/com/gisgraphy/domain/repository/RestaurantDao.java
1552
/******************************************************************************* * Gisgraphy Project * * 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 * * Copyright 2008 Gisgraphy project * David Masclet <davidmasclet@gisgraphy.com> * * *******************************************************************************/ package com.gisgraphy.domain.repository; import org.springframework.stereotype.Repository; import com.gisgraphy.domain.geoloc.entity.Restaurant; /** * A data access object for {@link Restaurant} Object * * @author <a href="mailto:david.masclet@gisgraphy.com">David Masclet</a> */ @Repository public class RestaurantDao extends GenericGisDao<Restaurant> implements IGisDao<Restaurant> { /** * Default constructor */ public RestaurantDao() { super(Restaurant.class); } }
lgpl-3.0
Blimster/three4g.wdl
net.blimster.gwt.threejs.wdl/src-gen/net/blimster/gwt/threejs/wdl/threeJsWrapperDescriptionLanguage/impl/ModelImpl.java
4092
/** * <copyright> * </copyright> * */ package net.blimster.gwt.threejs.wdl.threeJsWrapperDescriptionLanguage.impl; import java.util.Collection; import net.blimster.gwt.threejs.wdl.threeJsWrapperDescriptionLanguage.Model; import net.blimster.gwt.threejs.wdl.threeJsWrapperDescriptionLanguage.ObjectWrapper; import net.blimster.gwt.threejs.wdl.threeJsWrapperDescriptionLanguage.ThreeJsWrapperDescriptionLanguagePackage; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Model</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link net.blimster.gwt.threejs.wdl.threeJsWrapperDescriptionLanguage.impl.ModelImpl#getWrappers <em>Wrappers</em>}</li> * </ul> * </p> * * @generated */ public class ModelImpl extends MinimalEObjectImpl.Container implements Model { /** * The cached value of the '{@link #getWrappers() <em>Wrappers</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWrappers() * @generated * @ordered */ protected EList<ObjectWrapper> wrappers; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModelImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ThreeJsWrapperDescriptionLanguagePackage.Literals.MODEL; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ObjectWrapper> getWrappers() { if (wrappers == null) { wrappers = new EObjectContainmentEList<ObjectWrapper>(ObjectWrapper.class, this, ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS); } return wrappers; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS: return ((InternalEList<?>)getWrappers()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS: return getWrappers(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS: getWrappers().clear(); getWrappers().addAll((Collection<? extends ObjectWrapper>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS: getWrappers().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ThreeJsWrapperDescriptionLanguagePackage.MODEL__WRAPPERS: return wrappers != null && !wrappers.isEmpty(); } return super.eIsSet(featureID); } } //ModelImpl
lgpl-3.0
mobile-cloud-computing/ScalingMobileCodeOffloading
Framework-JVM/BackEnd/SurrogateJVM/src/main/java/edu/ut/mobile/network/CloudController.java
3189
/* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Please send inquiries to huber AT ut DOT ee */ package edu.ut.mobile.network; import java.lang.reflect.Method; import java.util.Vector; public class CloudController { private final String TAG = CloudController.class.getSimpleName(); private NetworkManagerClient NM = null; byte[] IPAddress = new byte[4]; // cloud address int port; // cloud port Object result = null; Object state = null; final Object waitob = new Object(); Vector results = new Vector(); public CloudController(){ port = NetInfo.port; IPAddress[0] = NetInfo.IPAddress[0]; IPAddress[1] = NetInfo.IPAddress[1]; IPAddress[2] = NetInfo.IPAddress[2]; IPAddress[3] = NetInfo.IPAddress[3]; //System.out.println(IPAddress[0] + "." + IPAddress[1] + "." + IPAddress[2] + "." + IPAddress[3]); } public Vector execute(Method toExecute, Object[] paramValues, Object state, Class stateDataType) { synchronized (waitob){ this.result = null; this.state = null; if(NM == null){ NM = new NetworkManagerClient(IPAddress, port); NM.setNmf(this); } new Thread(new StartNetwork(toExecute, paramValues, state, stateDataType)).start(); try { waitob.wait(NetInfo.waitTime); //System.out.println("Esperando"); } catch (InterruptedException e) { } if(this.state != null){ System.out.println("Finished offloaded task"); results.removeAllElements(); results.add(this.result); results.add(this.state); return results; }else{ System.out.println("Finished, but offloaded task result was not obtained"); return null; } } } public void setResult(Object result, Object cloudModel){ synchronized (waitob){ this.result = result; this.state = cloudModel; waitob.notify(); } } class StartNetwork implements Runnable{ Method toExecute; Class[] paramTypes; Object[] paramValues; Object state = null; Class stateDataType = null; public StartNetwork(Method toExecute, Object[] paramValues, Object state, Class stateDataType) { this.toExecute = toExecute; this.paramTypes = toExecute.getParameterTypes(); this.paramValues = paramValues; this.state = state; this.stateDataType = stateDataType; } @Override public void run() { boolean isconnected = NM.connect(); if(isconnected){ NM.send(toExecute.getName(), paramTypes, paramValues, state, stateDataType); } } } }
lgpl-3.0
SergiyKolesnikov/fuji
examples/GPL/WeightedOnlyVertices/GPL/Graph.java
761
package GPL; import java.util.LinkedList; // ************************************************************ public class Graph { // Adds an edge with weights public void addAnEdge( Vertex start, Vertex end, int weight ) { addEdge( start,end, weight ); } public void addEdge( Vertex start, Vertex end, int weight ) { addEdge( start,end ); // adds the start and end as adjacent start.addWeight( weight ); // the direction layer takes care of that // if the graph is undirected you have to include // the weight of the edge coming back if ( isDirected==false ) end.addWeight( weight ); } public void display() { original(); } }
lgpl-3.0
ChaoPang/molgenis
molgenis-jobs/src/test/java/org/molgenis/jobs/model/JobExecutionTest.java
2688
package org.molgenis.jobs.model; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.molgenis.data.AbstractMolgenisSpringTest; import org.molgenis.jobs.config.JobTestConfig; import org.molgenis.jobs.model.hello.HelloWorldJobExecution; import org.molgenis.jobs.model.hello.HelloWorldJobExecutionFactory; import org.molgenis.jobs.model.hello.HelloWorldJobExecutionMetadata; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; @ContextConfiguration(classes = { HelloWorldJobExecutionFactory.class, HelloWorldJobExecutionMetadata.class, JobExecutionMetaData.class, JobTestConfig.class }) public class JobExecutionTest extends AbstractMolgenisSpringTest { @Autowired private HelloWorldJobExecutionFactory factory; private HelloWorldJobExecution jobExecution; @BeforeMethod public void beforeMethod() { jobExecution = factory.create(); } @Test public void testAppendLog() throws Exception { String message1 = "Small message 1\n"; String message2 = "Small message 2\n"; ((JobExecution) jobExecution).appendLog(message1); ((JobExecution) jobExecution).appendLog(message2); assertEquals(jobExecution.getLog(), StringUtils.join(message1, message2)); } @Test public void testAppendLogTruncates() throws Exception { int i = 0; while (StringUtils.length(jobExecution.getLog()) < JobExecution.MAX_LOG_LENGTH) { ((JobExecution) jobExecution).appendLog("Small message " + i++ + "\n"); } String truncatedLog = jobExecution.getLog(); assertEquals(truncatedLog.length(), JobExecution.MAX_LOG_LENGTH, "Log message grows up to MAX_LOG_LENGTH"); assertTrue(truncatedLog.startsWith(JobExecution.TRUNCATION_BANNER), "Truncated log should start with TRUNCATION_BANNER"); assertTrue(truncatedLog.endsWith(JobExecution.TRUNCATION_BANNER), "Truncated log should end with TRUNCATION_BANNER"); ((JobExecution) jobExecution).appendLog("Ignored"); assertEquals(jobExecution.getLog(), truncatedLog, "Once truncated, the log should stop appending"); } @Test public void testSetProgressMessageAbbreviates() { String longMessage = RandomStringUtils.random(300); jobExecution.setProgressMessage(longMessage); String actual = jobExecution.getProgressMessage(); assertEquals(actual.length(), JobExecution.MAX_PROGRESS_MESSAGE_LENGTH); String common = StringUtils.getCommonPrefix(actual, longMessage); assertEquals(actual, common + "..."); } }
lgpl-3.0
marieke-bijlsma/molgenis
molgenis-ontology/src/main/java/org/molgenis/ontology/importer/OntologyImportService.java
5892
package org.molgenis.ontology.importer; import static java.util.Objects.requireNonNull; import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.molgenis.data.DataService; import org.molgenis.data.DatabaseAction; import org.molgenis.data.Entity; import org.molgenis.data.EntityMetaData; import org.molgenis.data.FileRepositoryCollectionFactory; import org.molgenis.data.MolgenisDataException; import org.molgenis.data.Repository; import org.molgenis.data.RepositoryCollection; import org.molgenis.data.elasticsearch.SearchService; import org.molgenis.data.importer.EntitiesValidationReportImpl; import org.molgenis.data.importer.ImportService; import org.molgenis.data.meta.MetaDataService; import org.molgenis.data.support.GenericImporterExtensions; import org.molgenis.data.support.QueryImpl; import org.molgenis.file.FileStore; import org.molgenis.framework.db.EntitiesValidationReport; import org.molgenis.framework.db.EntityImportReport; import org.molgenis.ontology.core.meta.OntologyMetaData; import org.molgenis.security.permission.PermissionSystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; @Service public class OntologyImportService implements ImportService { private final DataService dataService; private final SearchService searchService; private final PermissionSystemService permissionSystemService; @Autowired private FileStore fileStore; @Autowired public OntologyImportService(FileRepositoryCollectionFactory fileRepositoryCollectionFactory, DataService dataService, SearchService searchService, PermissionSystemService permissionSystemService) { this.dataService = requireNonNull(dataService); this.searchService = requireNonNull(searchService); this.permissionSystemService = requireNonNull(permissionSystemService); } @Override @Transactional public EntityImportReport doImport(RepositoryCollection source, DatabaseAction databaseAction, String defaultPackage) { if (databaseAction != DatabaseAction.ADD) throw new IllegalArgumentException("Only ADD is supported"); List<EntityMetaData> addedEntities = Lists.newArrayList(); EntityImportReport report = new EntityImportReport(); try { Iterator<String> it = source.getEntityNames().iterator(); while (it.hasNext()) { String entityNameToImport = it.next(); Repository repo = source.getRepository(entityNameToImport); try { report = new EntityImportReport(); Repository crudRepository = dataService.getRepository(entityNameToImport); crudRepository.add(repo.stream()); List<String> entityNames = addedEntities.stream().map(emd -> emd.getName()) .collect(Collectors.toList()); permissionSystemService.giveUserEntityPermissions(SecurityContextHolder.getContext(), entityNames); int count = 1; for (String entityName : entityNames) { report.addEntityCount(entityName, count++); } } finally { IOUtils.closeQuietly(repo); } } } catch (Exception e) { // Remove created repositories for (EntityMetaData emd : addedEntities) { if (dataService.hasRepository(emd.getName())) { dataService.deleteAll(emd.getName()); } if (searchService.hasMapping(emd)) { searchService.delete(emd.getName()); } } throw new MolgenisDataException(e); } return report; } @Override /** * Ontology validation */ public EntitiesValidationReport validateImport(File file, RepositoryCollection source) { EntitiesValidationReport report = new EntitiesValidationReportImpl(); if (source.getRepository(OntologyMetaData.ENTITY_NAME) == null) throw new MolgenisDataException("Exception Repository [" + OntologyMetaData.ENTITY_NAME + "] is missing"); boolean ontologyExists = false; for (Entity ontologyEntity : source.getRepository(OntologyMetaData.ENTITY_NAME)) { String ontologyIRI = ontologyEntity.getString(OntologyMetaData.ONTOLOGY_IRI); String ontologyName = ontologyEntity.getString(OntologyMetaData.ONTOLOGY_NAME); Entity ontologyQueryEntity = dataService.findOne(OntologyMetaData.ENTITY_NAME, new QueryImpl().eq(OntologyMetaData.ONTOLOGY_IRI, ontologyIRI).or() .eq(OntologyMetaData.ONTOLOGY_NAME, ontologyName)); ontologyExists = ontologyQueryEntity != null; } if(ontologyExists) throw new MolgenisDataException("The ontology you are trying to import already exists"); Iterator<String> it = source.getEntityNames().iterator(); while (it.hasNext()) { String entityName = it.next(); report.getSheetsImportable().put(entityName, !ontologyExists); } return report; } @Override public boolean canImport(File file, RepositoryCollection source) { for (String extension : GenericImporterExtensions.getOntology()) { if (file.getName().toLowerCase().endsWith(extension)) { return true; } } return false; } @Override public int getOrder() { return 10; } @Override public List<DatabaseAction> getSupportedDatabaseActions() { return Lists.newArrayList(DatabaseAction.ADD); } @Override public boolean getMustChangeEntityName() { return false; } @Override public Set<String> getSupportedFileExtensions() { return GenericImporterExtensions.getOntology(); } @Override public LinkedHashMap<String, Boolean> integrationTestMetaData(MetaDataService metaDataService, RepositoryCollection repositoryCollection, String defaultPackage) { return metaDataService.integrationTestMetaData(repositoryCollection); } }
lgpl-3.0
eixom/zoeey
src/main/java/org/zoeey/plugins/FireJavaSimple.java
3100
/* * MoXie (SysTem128@GMail.Com) 2009-4-21 0:39:54 * * Copyright &copy; 2008-2009 Zoeey.Org * Code license: GNU Lesser General Public License Version 3 * http://www.gnu.org/licenses/lgpl-3.0.txt */ package org.zoeey.plugins; import javax.servlet.http.HttpServletResponse; import org.zoeey.common.Version; import org.zoeey.common.container.ObjectHolder; import org.zoeey.util.JsonHelper; /** * <pre> * 将obj发送至FireBug控制台。同<a href="http://www.getfirebug.com/">FirePHP</a>的 FB::log 。 * <a href="http://www.getfirebug.com/">FirePHP</a> * <a href="http://www.firephp.org/">FireBug</a> *</pre> * @author MoXie(SysTem128@GMail.Com) */ public class FireJavaSimple { private static final String version = "0.2.1"; private FireJavaSimple() { } /** * LOG 信息 * @param response * @param obj */ public static final void log(HttpServletResponse response, Object obj) { log(response, obj, "LOG"); } /** * WARN 信息 * @param response * @param obj */ public static final void warn(HttpServletResponse response, Object obj) { log(response, obj, "WARN"); } /** * ERROR 信息 * @param response * @param obj */ public static final void error(HttpServletResponse response, Object obj) { log(response, obj, "ERROR"); } /** * INFO 信息 * @param response * @param obj */ public static final void info(HttpServletResponse response, Object obj) { log(response, obj, "INFO"); } /** * * <pre> * 将obj发送至FireBug控制台。同<a href="http://www.getfirebug.com/">FirePHP</a>的 FB::log 。 * <a href="http://www.getfirebug.com/">FirePHP</a> * <a href="http://www.firephp.org/">FireBug</a> *</pre> * @param response * @param obj */ private static final void log(HttpServletResponse response, Object obj, String type) { int i = ObjectHolder.<Integer>get("FireJavaSimple_index", 0); i++; ObjectHolder.put("FireJavaSimple_index", i); if (i == 1) { response.setHeader("X-Powered-By", "Zoeey/" + Version.VERSION); response.setHeader("X-Wf-Protocol-1", "http://meta.wildfirehq.org/Protocol/JsonStream/0.2"); response.setHeader("X-Wf-1-Plugin-1", "http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/" + version); response.setHeader("X-Wf-1-Structure-1", "http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1"); } StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("[{\"Type\":\""); msgBuilder.append(type); msgBuilder.append("\"},"); msgBuilder.append(JsonHelper.encode(obj)); msgBuilder.append(']'); response.setHeader("X-Wf-1-1-1-" + i, String.format("%d|%s|", msgBuilder.length(),msgBuilder.toString())); response.setIntHeader("X-Wf-1-Index", i); } }
lgpl-3.0
christianhujer/japi
historic2/src/test/net/sf/japi/cstyle/CStyleTest.java
2138
/* * Copyright (C) 2009 Christian Hujer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package test.net.sf.japi.cstyle; import net.sf.japi.cstyle.CStyle; import org.junit.Assert; import org.junit.Test; /** Unit test for {@link CStyle}. * @author <a href="mailto:cher@riedquat.de">Christian Hujer</a> */ public class CStyleTest { /** Tests that {@link CStyle#parse(char)} works. */ @Test public void testParse() { final CStyle testling = new CStyle(); final String testString = "if (foo > 'x') { // check x\n printf(\"%d\");\n}"; final char[] chars = testString.toCharArray(); for (final char c : chars) { testling.parse(c); } Assert.assertEquals("mode now must be NORMAL.", CStyle.PhysicalMode.NORMAL, testling.getPhysicalMode()); } /** Tests that {@link CStyle#reset()} works. */ @Test public void testReset() { final CStyle testling = new CStyle(); testling.parse('\''); Assert.assertEquals("previous mode must stay NORMAL.", CStyle.PhysicalMode.NORMAL, testling.getPreviousPhysicalMode()); Assert.assertEquals("mode now must be CHAR.", CStyle.PhysicalMode.CHAR, testling.getPhysicalMode()); testling.reset(); Assert.assertEquals("After reset, mode must be NORMAL", CStyle.PhysicalMode.NORMAL, testling.getPhysicalMode()); Assert.assertEquals("After reset, previous mode must be NORMAL", CStyle.PhysicalMode.NORMAL, testling.getPreviousPhysicalMode()); } } // class CStyleTest
lgpl-3.0
margaritis/gs-core
src/org/graphstream/stream/file/FileSourceDGS.java
3939
/* * Copyright 2006 - 2013 * Stefan Balev <stefan.balev@graphstream-project.org> * Julien Baudry <julien.baudry@graphstream-project.org> * Antoine Dutot <antoine.dutot@graphstream-project.org> * Yoann Pigné <yoann.pigne@graphstream-project.org> * Guilhelm Savin <guilhelm.savin@graphstream-project.org> * * This file is part of GraphStream <http://graphstream-project.org>. * * GraphStream is a library whose purpose is to handle static or dynamic * graph, create them from scratch, file or any source and display them. * * This program is free software distributed under the terms of two licenses, the * CeCILL-C license that fits European law, and the GNU Lesser General Public * License. You can use, modify and/ or redistribute the software under the terms * of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following * URL <http://www.cecill.info> or under the terms of the GNU LGPL 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, see <http://www.gnu.org/licenses/>. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C and LGPL licenses and that you accept their terms. */ package org.graphstream.stream.file; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.zip.GZIPInputStream; import org.graphstream.stream.file.dgs.DGSParser; import org.graphstream.util.parser.ParseException; import org.graphstream.util.parser.Parser; import org.graphstream.util.parser.ParserFactory; /** * Class responsible for parsing files in the DGS format. * * <p> * The DGS file format is especially designed for storing dynamic graph * definitions into a file. More information about the DGS file format will be * found on the GraphStream web site: <a * href="http://graphstream-project.org/">http://graphstream-project.org/</a> * </p> * * The usual file name extension used for this format is ".dgs". * * @see FileSource */ public class FileSourceDGS extends FileSourceParser { /* * (non-Javadoc) * * @see org.graphstream.stream.file.FileSourceParser#getNewParserFactory() */ public ParserFactory getNewParserFactory() { return new ParserFactory() { public Parser newParser(Reader reader) { return new DGSParser(FileSourceDGS.this, reader); } }; } @Override public boolean nextStep() throws IOException { try { return ((DGSParser) parser).nextStep(); } catch (ParseException e) { throw new IOException(e); } } @Override protected Reader createReaderForFile(String filename) throws IOException { InputStream is = null; is = new FileInputStream(filename); if (is.markSupported()) is.mark(128); try { is = new GZIPInputStream(is); } catch (IOException e1) { // // This is not a gzip input. // But gzip has eat some bytes so we reset the stream // or close and open it again. // if (is.markSupported()) { try { is.reset(); } catch (IOException e2) { // // Dirty but we hope do not get there // e2.printStackTrace(); } } else { try { is.close(); } catch (IOException e2) { // // Dirty but we hope do not get there // e2.printStackTrace(); } is = new FileInputStream(filename); } } return new BufferedReader(new InputStreamReader(is)); } }
lgpl-3.0
simeshev/parabuild-ci
3rdparty/findbugs086src/src/java/edu/umd/cs/findbugs/ClassMatcher.java
1425
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003,2004 University of Maryland * * 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 */ package edu.umd.cs.findbugs; public class ClassMatcher implements Matcher { private static final boolean DEBUG = Boolean.getBoolean("filter.debug"); private String className; public ClassMatcher(String className) { this.className = className; } public boolean match(BugInstance bugInstance) { ClassAnnotation primaryClassAnnotation = bugInstance.getPrimaryClass(); String bugClassName = primaryClassAnnotation.getClassName(); if (DEBUG) System.out.println("Compare " + bugClassName + " with " + className); return bugClassName.equals(className); } } // vim:ts=4
lgpl-3.0
nativelibs4java/JNAerator
ochafik-swing/src/main/java/com/ochafik/swing/syntaxcoloring/PerlTokenMarker.java
20534
package com.ochafik.swing.syntaxcoloring; import javax.swing.text.Segment; /** * Perl token marker. * * @author Slava Pestov * @version $Id: PerlTokenMarker.java,v 1.11 1999/12/13 03:40:30 sp Exp $ */ public class PerlTokenMarker extends TokenMarker { // public members public static final byte S_ONE = Token.INTERNAL_FIRST; public static final byte S_TWO = (byte)(Token.INTERNAL_FIRST + 1); public static final byte S_END = (byte)(Token.INTERNAL_FIRST + 2); public PerlTokenMarker() { this(getKeywords()); } public PerlTokenMarker(KeywordMap keywords) { this.keywords = keywords; } public byte markTokensImpl(byte _token, Segment line, int lineIndex) { char[] array = line.array; int offset = line.offset; token = _token; lastOffset = offset; lastKeyword = offset; matchChar = '\0'; matchCharBracket = false; matchSpacesAllowed = false; int length = line.count + offset; if(token == Token.LITERAL1 && lineIndex != 0 && lineInfo[lineIndex - 1].obj != null) { String str = (String)lineInfo[lineIndex - 1].obj; if(str != null && str.length() == line.count && SyntaxUtilities.regionMatches(false,line, offset,str)) { addToken(line.count,token); return Token.NULL; } else { addToken(line.count,token); lineInfo[lineIndex].obj = str; return token; } } boolean backslash = false; loop: for(int i = offset; i < length; i++) { int i1 = (i+1); char c = array[i]; if(c == '\\') { backslash = !backslash; continue; } switch(token) { case Token.NULL: switch(c) { case '#': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); addToken(length - i,Token.COMMENT1); lastOffset = lastKeyword = length; break loop; } break; case '=': backslash = false; if(i == offset) { token = Token.COMMENT2; addToken(length - i,token); lastOffset = lastKeyword = length; break loop; } else doKeyword(line,i,c); break; case '$': case '&': case '%': case '@': backslash = false; if(doKeyword(line,i,c)) break; if(length - i > 1) { if(c == '&' && (array[i1] == '&' || Character.isWhitespace( array[i1]))) i++; else { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; token = Token.KEYWORD2; } } break; case '"': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.LITERAL1; lineInfo[lineIndex].obj = null; lastOffset = lastKeyword = i; } break; case '\'': if(backslash) backslash = false; else { int oldLastKeyword = lastKeyword; if(doKeyword(line,i,c)) break; if(i != oldLastKeyword) break; addToken(i - lastOffset,token); token = Token.LITERAL2; lastOffset = lastKeyword = i; } break; case '`': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { addToken(i - lastOffset,token); token = Token.OPERATOR; lastOffset = lastKeyword = i; } break; case '<': if(doKeyword(line,i,c)) break; if(backslash) backslash = false; else { if(length - i > 2 && array[i1] == '<' && !Character.isWhitespace(array[i+2])) { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; token = Token.LITERAL1; int len = length - (i+2); if(array[length - 1] == ';') len--; lineInfo[lineIndex].obj = createReadinString(array,i + 2,len); } } break; case ':': backslash = false; if(doKeyword(line,i,c)) break; // Doesn't pick up all labels, // but at least doesn't mess up // XXX::YYY if(lastKeyword != 0) break; addToken(i1 - lastOffset,Token.LABEL); lastOffset = lastKeyword = i1; break; case '-': backslash = false; if(doKeyword(line,i,c)) break; if(i != lastKeyword || length - i <= 1) break; switch(array[i1]) { case 'r': case 'w': case 'x': case 'o': case 'R': case 'W': case 'X': case 'O': case 'e': case 'z': case 's': case 'f': case 'd': case 'l': case 'p': case 'S': case 'b': case 'c': case 't': case 'u': case 'g': case 'k': case 'T': case 'B': case 'M': case 'A': case 'C': addToken(i - lastOffset,token); addToken(2,Token.KEYWORD3); lastOffset = lastKeyword = i+2; i++; } break; case '/': case '?': if(doKeyword(line,i,c)) break; if(length - i > 1) { backslash = false; char ch = array[i1]; if(Character.isWhitespace(ch)) break; matchChar = c; matchSpacesAllowed = false; addToken(i - lastOffset,token); token = S_ONE; lastOffset = lastKeyword = i; } break; default: backslash = false; if(!Character.isLetterOrDigit(c) && c != '_') doKeyword(line,i,c); break; } break; case Token.KEYWORD2: backslash = false; // This test checks for an end-of-variable // condition if(!Character.isLetterOrDigit(c) && c != '_' && c != '#' && c != '\'' && c != ':' && c != '&') { // If this is the first character // of the variable name ($'aaa) // ignore it if(i != offset && array[i-1] == '$') { addToken(i1 - lastOffset,token); lastOffset = lastKeyword = i1; } // Otherwise, end of variable... else { addToken(i - lastOffset,token); lastOffset = lastKeyword = i; // Wind back so that stuff // like $hello$fred is picked // up i--; token = Token.NULL; } } break; case S_ONE: case S_TWO: if(backslash) backslash = false; else { if(matchChar == '\0') { if(Character.isWhitespace(matchChar) && !matchSpacesAllowed) break; else matchChar = c; } else { switch(matchChar) { case '(': matchChar = ')'; matchCharBracket = true; break; case '[': matchChar = ']'; matchCharBracket = true; break; case '{': matchChar = '}'; matchCharBracket = true; break; case '<': matchChar = '>'; matchCharBracket = true; break; default: matchCharBracket = false; break; } if(c != matchChar) break; if(token == S_TWO) { token = S_ONE; if(matchCharBracket) matchChar = '\0'; } else { token = S_END; addToken(i1 - lastOffset, Token.LITERAL2); lastOffset = lastKeyword = i1; } } } break; case S_END: backslash = false; if(!Character.isLetterOrDigit(c) && c != '_') doKeyword(line,i,c); break; case Token.COMMENT2: backslash = false; if(i == offset) { addToken(line.count,token); if(length - i > 3 && SyntaxUtilities .regionMatches(false,line,offset,"=cut")) token = Token.NULL; lastOffset = lastKeyword = length; break loop; } break; case Token.LITERAL1: if(backslash) backslash = false; /* else if(c == '$') backslash = true; */ else if(c == '"') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.LITERAL2: if(backslash) backslash = false; /* else if(c == '$') backslash = true; */ else if(c == '\'') { addToken(i1 - lastOffset,Token.LITERAL1); token = Token.NULL; lastOffset = lastKeyword = i1; } break; case Token.OPERATOR: if(backslash) backslash = false; else if(c == '`') { addToken(i1 - lastOffset,token); token = Token.NULL; lastOffset = lastKeyword = i1; } break; default: throw new InternalError("Invalid state: " + token); } } if(token == Token.NULL) doKeyword(line,length,'\0'); switch(token) { case Token.KEYWORD2: addToken(length - lastOffset,token); token = Token.NULL; break; case Token.LITERAL2: addToken(length - lastOffset,Token.LITERAL1); break; case S_END: addToken(length - lastOffset,Token.LITERAL2); token = Token.NULL; break; case S_ONE: case S_TWO: addToken(length - lastOffset,Token.INVALID); // XXX token = Token.NULL; break; default: addToken(length - lastOffset,token); break; } return token; } // private members private KeywordMap keywords; private byte token; private int lastOffset; private int lastKeyword; private char matchChar; private boolean matchCharBracket; private boolean matchSpacesAllowed; private boolean doKeyword(Segment line, int i, char c) { int i1 = i+1; if(token == S_END) { addToken(i - lastOffset,Token.LITERAL2); token = Token.NULL; lastOffset = i; lastKeyword = i1; return false; } int len = i - lastKeyword; byte id = keywords.lookup(line,lastKeyword,len); if(id == S_ONE || id == S_TWO) { if(lastKeyword != lastOffset) addToken(lastKeyword - lastOffset,Token.NULL); addToken(len,Token.LITERAL2); lastOffset = i; lastKeyword = i1; if(Character.isWhitespace(c)) matchChar = '\0'; else matchChar = c; matchSpacesAllowed = true; token = id; return true; } else if(id != Token.NULL) { if(lastKeyword != lastOffset) addToken(lastKeyword - lastOffset,Token.NULL); addToken(len,id); lastOffset = i; } lastKeyword = i1; return false; } // Converts < EOF >, < 'EOF' >, etc to <EOF> private String createReadinString(char[] array, int start, int len) { int idx1 = start; int idx2 = start + len - 1; while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx1]))) idx1++; while((idx1 <= idx2) && (!Character.isLetterOrDigit(array[idx2]))) idx2--; return new String(array, idx1, idx2 - idx1 + 1); } private static KeywordMap perlKeywords; private static KeywordMap getKeywords() { if(perlKeywords == null) { perlKeywords = new KeywordMap(false); perlKeywords.add("my",Token.KEYWORD1); perlKeywords.add("local",Token.KEYWORD1); perlKeywords.add("new",Token.KEYWORD1); perlKeywords.add("if",Token.KEYWORD1); perlKeywords.add("until",Token.KEYWORD1); perlKeywords.add("while",Token.KEYWORD1); perlKeywords.add("elsif",Token.KEYWORD1); perlKeywords.add("else",Token.KEYWORD1); perlKeywords.add("eval",Token.KEYWORD1); perlKeywords.add("unless",Token.KEYWORD1); perlKeywords.add("foreach",Token.KEYWORD1); perlKeywords.add("continue",Token.KEYWORD1); perlKeywords.add("exit",Token.KEYWORD1); perlKeywords.add("die",Token.KEYWORD1); perlKeywords.add("last",Token.KEYWORD1); perlKeywords.add("goto",Token.KEYWORD1); perlKeywords.add("next",Token.KEYWORD1); perlKeywords.add("redo",Token.KEYWORD1); perlKeywords.add("goto",Token.KEYWORD1); perlKeywords.add("return",Token.KEYWORD1); perlKeywords.add("do",Token.KEYWORD1); perlKeywords.add("sub",Token.KEYWORD1); perlKeywords.add("use",Token.KEYWORD1); perlKeywords.add("require",Token.KEYWORD1); perlKeywords.add("package",Token.KEYWORD1); perlKeywords.add("BEGIN",Token.KEYWORD1); perlKeywords.add("END",Token.KEYWORD1); perlKeywords.add("eq",Token.OPERATOR); perlKeywords.add("ne",Token.OPERATOR); perlKeywords.add("not",Token.OPERATOR); perlKeywords.add("and",Token.OPERATOR); perlKeywords.add("or",Token.OPERATOR); perlKeywords.add("abs",Token.KEYWORD3); perlKeywords.add("accept",Token.KEYWORD3); perlKeywords.add("alarm",Token.KEYWORD3); perlKeywords.add("atan2",Token.KEYWORD3); perlKeywords.add("bind",Token.KEYWORD3); perlKeywords.add("binmode",Token.KEYWORD3); perlKeywords.add("bless",Token.KEYWORD3); perlKeywords.add("caller",Token.KEYWORD3); perlKeywords.add("chdir",Token.KEYWORD3); perlKeywords.add("chmod",Token.KEYWORD3); perlKeywords.add("chomp",Token.KEYWORD3); perlKeywords.add("chr",Token.KEYWORD3); perlKeywords.add("chroot",Token.KEYWORD3); perlKeywords.add("chown",Token.KEYWORD3); perlKeywords.add("closedir",Token.KEYWORD3); perlKeywords.add("close",Token.KEYWORD3); perlKeywords.add("connect",Token.KEYWORD3); perlKeywords.add("cos",Token.KEYWORD3); perlKeywords.add("crypt",Token.KEYWORD3); perlKeywords.add("dbmclose",Token.KEYWORD3); perlKeywords.add("dbmopen",Token.KEYWORD3); perlKeywords.add("defined",Token.KEYWORD3); perlKeywords.add("delete",Token.KEYWORD3); perlKeywords.add("die",Token.KEYWORD3); perlKeywords.add("dump",Token.KEYWORD3); perlKeywords.add("each",Token.KEYWORD3); perlKeywords.add("endgrent",Token.KEYWORD3); perlKeywords.add("endhostent",Token.KEYWORD3); perlKeywords.add("endnetent",Token.KEYWORD3); perlKeywords.add("endprotoent",Token.KEYWORD3); perlKeywords.add("endpwent",Token.KEYWORD3); perlKeywords.add("endservent",Token.KEYWORD3); perlKeywords.add("eof",Token.KEYWORD3); perlKeywords.add("exec",Token.KEYWORD3); perlKeywords.add("exists",Token.KEYWORD3); perlKeywords.add("exp",Token.KEYWORD3); perlKeywords.add("fctnl",Token.KEYWORD3); perlKeywords.add("fileno",Token.KEYWORD3); perlKeywords.add("flock",Token.KEYWORD3); perlKeywords.add("fork",Token.KEYWORD3); perlKeywords.add("format",Token.KEYWORD3); perlKeywords.add("formline",Token.KEYWORD3); perlKeywords.add("getc",Token.KEYWORD3); perlKeywords.add("getgrent",Token.KEYWORD3); perlKeywords.add("getgrgid",Token.KEYWORD3); perlKeywords.add("getgrnam",Token.KEYWORD3); perlKeywords.add("gethostbyaddr",Token.KEYWORD3); perlKeywords.add("gethostbyname",Token.KEYWORD3); perlKeywords.add("gethostent",Token.KEYWORD3); perlKeywords.add("getlogin",Token.KEYWORD3); perlKeywords.add("getnetbyaddr",Token.KEYWORD3); perlKeywords.add("getnetbyname",Token.KEYWORD3); perlKeywords.add("getnetent",Token.KEYWORD3); perlKeywords.add("getpeername",Token.KEYWORD3); perlKeywords.add("getpgrp",Token.KEYWORD3); perlKeywords.add("getppid",Token.KEYWORD3); perlKeywords.add("getpriority",Token.KEYWORD3); perlKeywords.add("getprotobyname",Token.KEYWORD3); perlKeywords.add("getprotobynumber",Token.KEYWORD3); perlKeywords.add("getprotoent",Token.KEYWORD3); perlKeywords.add("getpwent",Token.KEYWORD3); perlKeywords.add("getpwnam",Token.KEYWORD3); perlKeywords.add("getpwuid",Token.KEYWORD3); perlKeywords.add("getservbyname",Token.KEYWORD3); perlKeywords.add("getservbyport",Token.KEYWORD3); perlKeywords.add("getservent",Token.KEYWORD3); perlKeywords.add("getsockname",Token.KEYWORD3); perlKeywords.add("getsockopt",Token.KEYWORD3); perlKeywords.add("glob",Token.KEYWORD3); perlKeywords.add("gmtime",Token.KEYWORD3); perlKeywords.add("grep",Token.KEYWORD3); perlKeywords.add("hex",Token.KEYWORD3); perlKeywords.add("import",Token.KEYWORD3); perlKeywords.add("index",Token.KEYWORD3); perlKeywords.add("int",Token.KEYWORD3); perlKeywords.add("ioctl",Token.KEYWORD3); perlKeywords.add("join",Token.KEYWORD3); perlKeywords.add("keys",Token.KEYWORD3); perlKeywords.add("kill",Token.KEYWORD3); perlKeywords.add("lcfirst",Token.KEYWORD3); perlKeywords.add("lc",Token.KEYWORD3); perlKeywords.add("length",Token.KEYWORD3); perlKeywords.add("link",Token.KEYWORD3); perlKeywords.add("listen",Token.KEYWORD3); perlKeywords.add("log",Token.KEYWORD3); perlKeywords.add("localtime",Token.KEYWORD3); perlKeywords.add("lstat",Token.KEYWORD3); perlKeywords.add("map",Token.KEYWORD3); perlKeywords.add("mkdir",Token.KEYWORD3); perlKeywords.add("msgctl",Token.KEYWORD3); perlKeywords.add("msgget",Token.KEYWORD3); perlKeywords.add("msgrcv",Token.KEYWORD3); perlKeywords.add("no",Token.KEYWORD3); perlKeywords.add("oct",Token.KEYWORD3); perlKeywords.add("opendir",Token.KEYWORD3); perlKeywords.add("open",Token.KEYWORD3); perlKeywords.add("ord",Token.KEYWORD3); perlKeywords.add("pack",Token.KEYWORD3); perlKeywords.add("pipe",Token.KEYWORD3); perlKeywords.add("pop",Token.KEYWORD3); perlKeywords.add("pos",Token.KEYWORD3); perlKeywords.add("printf",Token.KEYWORD3); perlKeywords.add("print",Token.KEYWORD3); perlKeywords.add("push",Token.KEYWORD3); perlKeywords.add("quotemeta",Token.KEYWORD3); perlKeywords.add("rand",Token.KEYWORD3); perlKeywords.add("readdir",Token.KEYWORD3); perlKeywords.add("read",Token.KEYWORD3); perlKeywords.add("readlink",Token.KEYWORD3); perlKeywords.add("recv",Token.KEYWORD3); perlKeywords.add("ref",Token.KEYWORD3); perlKeywords.add("rename",Token.KEYWORD3); perlKeywords.add("reset",Token.KEYWORD3); perlKeywords.add("reverse",Token.KEYWORD3); perlKeywords.add("rewinddir",Token.KEYWORD3); perlKeywords.add("rindex",Token.KEYWORD3); perlKeywords.add("rmdir",Token.KEYWORD3); perlKeywords.add("scalar",Token.KEYWORD3); perlKeywords.add("seekdir",Token.KEYWORD3); perlKeywords.add("seek",Token.KEYWORD3); perlKeywords.add("select",Token.KEYWORD3); perlKeywords.add("semctl",Token.KEYWORD3); perlKeywords.add("semget",Token.KEYWORD3); perlKeywords.add("semop",Token.KEYWORD3); perlKeywords.add("send",Token.KEYWORD3); perlKeywords.add("setgrent",Token.KEYWORD3); perlKeywords.add("sethostent",Token.KEYWORD3); perlKeywords.add("setnetent",Token.KEYWORD3); perlKeywords.add("setpgrp",Token.KEYWORD3); perlKeywords.add("setpriority",Token.KEYWORD3); perlKeywords.add("setprotoent",Token.KEYWORD3); perlKeywords.add("setpwent",Token.KEYWORD3); perlKeywords.add("setsockopt",Token.KEYWORD3); perlKeywords.add("shift",Token.KEYWORD3); perlKeywords.add("shmctl",Token.KEYWORD3); perlKeywords.add("shmget",Token.KEYWORD3); perlKeywords.add("shmread",Token.KEYWORD3); perlKeywords.add("shmwrite",Token.KEYWORD3); perlKeywords.add("shutdown",Token.KEYWORD3); perlKeywords.add("sin",Token.KEYWORD3); perlKeywords.add("sleep",Token.KEYWORD3); perlKeywords.add("socket",Token.KEYWORD3); perlKeywords.add("socketpair",Token.KEYWORD3); perlKeywords.add("sort",Token.KEYWORD3); perlKeywords.add("splice",Token.KEYWORD3); perlKeywords.add("split",Token.KEYWORD3); perlKeywords.add("sprintf",Token.KEYWORD3); perlKeywords.add("sqrt",Token.KEYWORD3); perlKeywords.add("srand",Token.KEYWORD3); perlKeywords.add("stat",Token.KEYWORD3); perlKeywords.add("study",Token.KEYWORD3); perlKeywords.add("substr",Token.KEYWORD3); perlKeywords.add("symlink",Token.KEYWORD3); perlKeywords.add("syscall",Token.KEYWORD3); perlKeywords.add("sysopen",Token.KEYWORD3); perlKeywords.add("sysread",Token.KEYWORD3); perlKeywords.add("syswrite",Token.KEYWORD3); perlKeywords.add("telldir",Token.KEYWORD3); perlKeywords.add("tell",Token.KEYWORD3); perlKeywords.add("tie",Token.KEYWORD3); perlKeywords.add("tied",Token.KEYWORD3); perlKeywords.add("time",Token.KEYWORD3); perlKeywords.add("times",Token.KEYWORD3); perlKeywords.add("truncate",Token.KEYWORD3); perlKeywords.add("uc",Token.KEYWORD3); perlKeywords.add("ucfirst",Token.KEYWORD3); perlKeywords.add("umask",Token.KEYWORD3); perlKeywords.add("undef",Token.KEYWORD3); perlKeywords.add("unlink",Token.KEYWORD3); perlKeywords.add("unpack",Token.KEYWORD3); perlKeywords.add("unshift",Token.KEYWORD3); perlKeywords.add("untie",Token.KEYWORD3); perlKeywords.add("utime",Token.KEYWORD3); perlKeywords.add("values",Token.KEYWORD3); perlKeywords.add("vec",Token.KEYWORD3); perlKeywords.add("wait",Token.KEYWORD3); perlKeywords.add("waitpid",Token.KEYWORD3); perlKeywords.add("wantarray",Token.KEYWORD3); perlKeywords.add("warn",Token.KEYWORD3); perlKeywords.add("write",Token.KEYWORD3); perlKeywords.add("m",S_ONE); perlKeywords.add("q",S_ONE); perlKeywords.add("qq",S_ONE); perlKeywords.add("qw",S_ONE); perlKeywords.add("qx",S_ONE); perlKeywords.add("s",S_TWO); perlKeywords.add("tr",S_TWO); perlKeywords.add("y",S_TWO); } return perlKeywords; } }
lgpl-3.0
zakski/project-soisceal
2p-mvn/tuProlog-3.5-mvn/src/alice/tuprolog/json/ReducedEngineState.java
990
package alice.tuprolog.json; import alice.tuprolog.Term; //Alberto public class ReducedEngineState extends AbstractEngineState { @SuppressWarnings("unused") private String type = "ReducedEngineState"; @Override public void setQuery(Term query) { this.query = query; } @Override public Term getQuery(){ return this.query; } @Override public void setNumberAskedResults(int nResultAsked) { this.nAskedResults = nResultAsked; } @Override public int getNumberAskedResults(){ return this.nAskedResults; } @Override public void setHasOpenAlternatives(boolean hasOpenAlternatives) { this.hasOpenAlternatives = hasOpenAlternatives; } @Override public boolean hasOpenAlternatives(){ return this.hasOpenAlternatives; } @Override public long getSerializationTimestamp() { return serializationTimestamp; } @Override public void setSerializationTimestamp(long serializationTimestamp) { this.serializationTimestamp = serializationTimestamp; } }
lgpl-3.0
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
master/src/test/java/com/examples/with/different/packagename/mutation/MutationPropagation.java
1011
/** * Copyright (C) 2010-2015 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 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 Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package com.examples.with.different.packagename.mutation; public class MutationPropagation { private int x; public MutationPropagation(int y) { x = y; } public void inc() { x++; } public boolean isFoo() { return x == 5; } }
lgpl-3.0
nightscape/JMathLib
src/jmathlib/toolbox/string/_double.java
2760
package jmathlib.toolbox.string; /* This file is part or JMathLib * author: 2006/05/16 * */ import jmathlib.core.tokens.*; import jmathlib.core.tokens.numbertokens.*; import jmathlib.core.functions.ExternalFunction; import jmathlib.core.interpreter.GlobalValues; /**An external function for changing strings into numbers */ public class _double extends ExternalFunction { /**returns a matrix of numbers * @param operands[0] = string (e.g. ["hello"]) * @return a matrix of numbers */ public OperandToken evaluate(Token[] operands, GlobalValues globals) { // one operand if (getNArgIn(operands)!=1) throwMathLibException("_double: number of input arguments != 1"); if (operands[0] instanceof CharToken) { // get data from arguments String stringValue = ((CharToken)operands[0]).getValue(); // convert string to array of bytes byte[] b = stringValue.getBytes(); double[][] X = new double[1][b.length]; // convert array of byte to array of double for (int i=0; i<b.length; i++) { X[0][i]= (double)b[i]; } return new DoubleNumberToken( X ); } else if (operands[0] instanceof Int8NumberToken) { Int8NumberToken tok = (Int8NumberToken)operands[0]; DoubleNumberToken d = new DoubleNumberToken( tok.getSize(), null, null); for (int i=0; i<tok.getNumberOfElements(); i++) { d.setValue(i, tok.getValueRe(i), tok.getValueIm(i)); } return d; } else if (operands[0] instanceof UInt8NumberToken) { UInt8NumberToken tok = (UInt8NumberToken)operands[0]; DoubleNumberToken d = new DoubleNumberToken( tok.getSize(), null, null); for (int i=0; i<tok.getNumberOfElements(); i++) { d.setValue(i, tok.getValueRe(i), tok.getValueIm(i)); } return d; } else if (operands[0] instanceof DoubleNumberToken) { return (DoubleNumberToken)operands[0]; } else throwMathLibException("_double: wrong type of argument"); return null; } // end eval } /* @GROUP char @SYNTAX number = str2num( string ) @DOC Convert strings into numbers @EXAMPLES str2num("hello 12") returns [104, 101, 108, 108, 111, 32, 49, 50] @NOTES @SEE num2str, char */
lgpl-3.0
codeApeFromChina/resource
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/multilevel/Middle.java
2016
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * 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.hibernate.ejb.test.cascade.multilevel; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "MIDDLE") public class Middle { @Id private Long id; @ManyToOne private Top top; @OneToOne(cascade = { CascadeType.ALL }) @JoinColumn(name = "BOTTOM_ID") private Bottom bottom; private Middle() { } public Middle(Long i) { this.id = i; } Long getId() { return id; } void setId(Long id) { this.id = id; } Top getTop() { return top; } void setTop(Top top) { this.top = top; } Bottom getBottom() { return bottom; } void setBottom(Bottom bottom) { this.bottom = bottom; bottom.setMiddle(this); } }
unlicense
SleepyTrousers/EnderIO
enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/power/IPowerConduit.java
1006
package crazypants.enderio.conduits.conduit.power; import javax.annotation.Nonnull; import crazypants.enderio.base.conduit.IClientConduit; import crazypants.enderio.base.conduit.IExtractor; import crazypants.enderio.base.conduit.IServerConduit; import crazypants.enderio.base.power.IPowerInterface; import net.minecraft.util.EnumFacing; import net.minecraftforge.energy.IEnergyStorage; public interface IPowerConduit extends IEnergyStorage, IExtractor, IServerConduit, IClientConduit { public static final @Nonnull String ICON_KEY = "blocks/power_conduit"; public static final @Nonnull String ICON_CORE_KEY = "blocks/power_conduit_core"; public static final String COLOR_CONTROLLER_ID = "ColorController"; IPowerInterface getExternalPowerReceptor(@Nonnull EnumFacing direction); boolean getConnectionsDirty(); void setEnergyStored(int energy); int getMaxEnergyRecieved(@Nonnull EnumFacing dir); int getMaxEnergyExtracted(@Nonnull EnumFacing dir); void setConnectionsDirty(); }
unlicense
HenryLoenwind/EnderIO
enderio-base/src/main/java/crazypants/enderio/base/transceiver/Channel.java
2739
package crazypants.enderio.base.transceiver; import javax.annotation.Nonnull; import com.enderio.core.common.util.NullHelper; import com.enderio.core.common.util.UserIdent; import com.mojang.authlib.GameProfile; import info.loenwind.autosave.annotations.Factory; import info.loenwind.autosave.annotations.Storable; import info.loenwind.autosave.annotations.Store; import net.minecraft.nbt.NBTTagCompound; @Storable public class Channel { public static Channel readFromNBT(NBTTagCompound root) { String name = root.getString("name"); UserIdent user = UserIdent.readfromNbt(root, "user"); ChannelType type = NullHelper.notnullJ(ChannelType.values()[root.getShort("type")], "Enum.values()"); return name.isEmpty() ? null : new Channel(name, user, type); } @Store private final @Nonnull String name; @Store private final @Nonnull UserIdent user; @Store private final @Nonnull ChannelType type; public Channel(@Nonnull String name, @Nonnull UserIdent user, @Nonnull ChannelType type) { this.name = NullHelper.first(name.trim(), ""); this.user = user; this.type = type; } public Channel(@Nonnull String name, @Nonnull GameProfile profile, @Nonnull ChannelType type) { this(name, UserIdent.create(profile), type); } public Channel(@Nonnull String name, @Nonnull ChannelType type) { this(name, UserIdent.NOBODY, type); } @Factory private Channel() { this("(internal error)", ChannelType.ITEM); } public boolean isPublic() { return user == UserIdent.NOBODY; } public void writeToNBT(NBTTagCompound root) { if (name.isEmpty()) { return; } root.setString("name", name); user.saveToNbt(root, "user"); root.setShort("type", (short) type.ordinal()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); result = prime * result + type.hashCode(); result = prime * result + user.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; Channel other = (Channel) obj; if (!getName().equals(other.getName())) return false; if (type != other.type) return false; if (!user.equals(other.user)) return false; return true; } public @Nonnull String getName() { return name; } public @Nonnull ChannelType getType() { return type; } public @Nonnull UserIdent getUser() { return user; } @Override public String toString() { return "Channel [name=" + name + ", user=" + user + ", type=" + type + "]"; } }
unlicense
nevillelyh/DataflowJavaSDK
maven-archetypes/examples/src/main/resources/archetype-resources/src/main/java/WordCount.java
7119
/* * 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 ${package}; import ${package}.common.ExampleUtils; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.TextIO; import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation.Required; import org.apache.beam.sdk.transforms.Count; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; /** * An example that counts words in Shakespeare and includes Beam best practices. * * <p>This class, {@link WordCount}, is the second in a series of four successively more detailed * 'word count' examples. You may first want to take a look at {@link MinimalWordCount}. * After you've looked at this example, then see the {@link DebuggingWordCount} * pipeline, for introduction of additional concepts. * * <p>For a detailed walkthrough of this example, see * <a href="https://beam.apache.org/get-started/wordcount-example/"> * https://beam.apache.org/get-started/wordcount-example/ * </a> * * <p>Basic concepts, also in the MinimalWordCount example: * Reading text files; counting a PCollection; writing to text files * * <p>New Concepts: * <pre> * 1. Executing a Pipeline both locally and using the selected runner * 2. Using ParDo with static DoFns defined out-of-line * 3. Building a composite transform * 4. Defining your own pipeline options * </pre> * * <p>Concept #1: you can execute this pipeline either locally or using by selecting another runner. * These are now command-line options and not hard-coded as they were in the MinimalWordCount * example. * * <p>To change the runner, specify: * <pre>{@code * --runner=YOUR_SELECTED_RUNNER * } * </pre> * * <p>To execute this pipeline, specify a local output file (if using the * {@code DirectRunner}) or output prefix on a supported distributed file system. * <pre>{@code * --output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX] * }</pre> * * <p>The input file defaults to a public data set containing the text of of King Lear, * by William Shakespeare. You can override it and choose your own input with {@code --inputFile}. */ public class WordCount { /** * Concept #2: You can make your pipeline assembly code less verbose by defining your DoFns * statically out-of-line. This DoFn tokenizes lines of text into individual words; we pass it * to a ParDo in the pipeline. */ static class ExtractWordsFn extends DoFn<String, String> { private final Counter emptyLines = Metrics.counter(ExtractWordsFn.class, "emptyLines"); @ProcessElement public void processElement(ProcessContext c) { if (c.element().trim().isEmpty()) { emptyLines.inc(); } // Split the line into words. String[] words = c.element().split(ExampleUtils.TOKENIZER_PATTERN); // Output each word encountered into the output PCollection. for (String word : words) { if (!word.isEmpty()) { c.output(word); } } } } /** A SimpleFunction that converts a Word and Count into a printable string. */ public static class FormatAsTextFn extends SimpleFunction<KV<String, Long>, String> { @Override public String apply(KV<String, Long> input) { return input.getKey() + ": " + input.getValue(); } } /** * A PTransform that converts a PCollection containing lines of text into a PCollection of * formatted word counts. * * <p>Concept #3: This is a custom composite transform that bundles two transforms (ParDo and * Count) as a reusable PTransform subclass. Using composite transforms allows for easy reuse, * modular testing, and an improved monitoring experience. */ public static class CountWords extends PTransform<PCollection<String>, PCollection<KV<String, Long>>> { @Override public PCollection<KV<String, Long>> expand(PCollection<String> lines) { // Convert lines of text into individual words. PCollection<String> words = lines.apply( ParDo.of(new ExtractWordsFn())); // Count the number of times each word occurs. PCollection<KV<String, Long>> wordCounts = words.apply(Count.<String>perElement()); return wordCounts; } } /** * Options supported by {@link WordCount}. * * <p>Concept #4: Defining your own configuration options. Here, you can add your own arguments * to be processed by the command-line parser, and specify default values for them. You can then * access the options values in your pipeline code. * * <p>Inherits standard configuration options. */ public interface WordCountOptions extends PipelineOptions { /** * By default, this example reads from a public dataset containing the text of * King Lear. Set this option to choose a different input file or glob. */ @Description("Path of the file to read from") @Default.String("gs://apache-beam-samples/shakespeare/kinglear.txt") String getInputFile(); void setInputFile(String value); /** * Set this required option to specify where to write the output. */ @Description("Path of the file to write to") @Required String getOutput(); void setOutput(String value); } public static void main(String[] args) { WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation() .as(WordCountOptions.class); Pipeline p = Pipeline.create(options); // Concepts #2 and #3: Our pipeline applies the composite CountWords transform, and passes the // static FormatAsTextFn() to the ParDo transform. p.apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(new CountWords()) .apply(MapElements.via(new FormatAsTextFn())) .apply("WriteCounts", TextIO.write().to(options.getOutput())); p.run().waitUntilFinish(); } }
apache-2.0
hmmlopez/citrus
modules/citrus-core/src/main/java/com/consol/citrus/actions/WaitAction.java
5013
/* * Copyright 2006-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.actions; import com.consol.citrus.condition.Condition; import com.consol.citrus.context.TestContext; import com.consol.citrus.exceptions.CitrusRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.util.concurrent.*; /** * Pause the test execution until the condition is met or the wait time has been exceeded. * * @author Martin Maher * @since 2.4 */ public class WaitAction extends AbstractTestAction { /** Logger */ private static final Logger log = LoggerFactory.getLogger(WaitAction.class); /** Condition to be met */ private Condition condition; /** The total time to wait in seconds, for the condition to be met before failing */ private String seconds; /** The total time to wait in milliseconds, for the condition to be met before failing */ private String milliseconds = "5000"; /** The time interval in milliseconds between each test of the condition */ private String interval = "1000"; /** * Default constructor. */ public WaitAction() { setName("wait"); } @Override public void doExecute(final TestContext context) { Boolean conditionSatisfied = null; long timeLeft = getWaitTimeMs(context); long intervalMs = getIntervalMs(context); if (intervalMs > timeLeft) { intervalMs = timeLeft; } Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() { return condition.isSatisfied(context); } }; while (timeLeft > 0) { timeLeft -= intervalMs; if (log.isDebugEnabled()) { log.debug(String.format("Waiting for condition %s", condition.getName())); } ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(callable); long checkStartTime = System.currentTimeMillis(); try { conditionSatisfied = future.get(intervalMs, TimeUnit.MILLISECONDS); } catch (InterruptedException | TimeoutException | ExecutionException e) { log.warn(String.format("Condition check interrupted with '%s'", e.getClass().getSimpleName())); } executor.shutdown(); if (Boolean.TRUE.equals(conditionSatisfied)) { log.info(String.format(condition.getSuccessMessage(context))); return; } long sleepTime = intervalMs - (System.currentTimeMillis() - checkStartTime); if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { log.warn("Interrupted during wait!", e); } } } throw new CitrusRuntimeException(condition.getErrorMessage(context)); } /** * Gets total wait time in milliseconds. Either uses second time value or default milliseconds. * @param context * @return */ private long getWaitTimeMs(TestContext context) { if (StringUtils.hasText(seconds)) { return Long.valueOf(context.replaceDynamicContentInString(seconds)) * 1000; } else { return Long.valueOf(context.replaceDynamicContentInString(milliseconds)); } } /** * Gets the time interval for the condition check in milliseconds. * @param context * @return */ private long getIntervalMs(TestContext context) { return Long.valueOf(context.replaceDynamicContentInString(interval)); } public String getSeconds() { return seconds; } public void setSeconds(String seconds) { this.seconds = seconds; } public String getMilliseconds() { return milliseconds; } public void setMilliseconds(String milliseconds) { this.milliseconds = milliseconds; } public Condition getCondition() { return condition; } public void setCondition(Condition condition) { this.condition = condition; } public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } }
apache-2.0
lburgazzoli/apache-activemq-artemis
tests/activemq5-unit-tests/src/test/java/org/apache/activemq/openwire/v3/JournalTransactionTest.java
1930
/** * 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.activemq.openwire.v3; import org.apache.activemq.command.JournalTransaction; import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTransaction * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { public static final JournalTransactionTest SINGLETON = new JournalTransactionTest(); @Override public Object createObject() throws Exception { JournalTransaction info = new JournalTransaction(); populateObject(info); return info; } @Override protected void populateObject(Object object) throws Exception { super.populateObject(object); JournalTransaction info = (JournalTransaction) object; info.setTransactionId(createTransactionId("TransactionId:1")); info.setType((byte) 1); info.setWasPrepared(true); } }
apache-2.0
mgenov/sitebricks
stat/src/main/java/com/google/sitebricks/stat/StatRegistrar.java
3380
/** * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.sitebricks.stat; import com.google.common.collect.MapMaker; import java.lang.reflect.Member; import java.util.List; import java.util.Map; /** * A {@link StatRegistrar} offers the means by which to register a stat. * * @author ffaber@gmail.com (Fred Faber) */ public final class StatRegistrar { /** * The default exposer to use, which is suitable in most cases. * Note that this would be best defined within {@link Stat}, but * static fields declared within {@code @interface} definitions lead to * javac bugs, such as is described here: * https://bugs.eclipse.org/bugs/show_bug.cgi?id=324931 */ Class<? extends StatExposer> DEFAULT_EXPOSER_CLASS = StatExposers.InferenceExposer.class; private final Map<Class<?>, List<MemberAnnotatedWithAtStat>> classesToInstanceMembers = new MapMaker().weakKeys().makeComputingMap( new StatCollector( StatCollector.StaticMemberPolicy.EXCLUDE_STATIC_MEMBERS)); private final Map<Class<?>, List<MemberAnnotatedWithAtStat>> classesToStaticMembers = new MapMaker().weakKeys().makeComputingMap( new StatCollector( StatCollector.StaticMemberPolicy.INCLUDE_STATIC_MEMBERS)); private final Stats stats; StatRegistrar(Stats stats) { this.stats = stats; } public void registerSingleStat(String name, String description, Object stat) { registerSingleStat( name, description, StatReaders.forObject(stat), DEFAULT_EXPOSER_CLASS); } public void registerSingleStat( String name, String description, StatReader statReader, Class<? extends StatExposer> statExposerClass) { stats.register( StatDescriptor.of(name, description, statReader, statExposerClass)); } public void registerStaticStatsOn(Class<?> clazz) { List<MemberAnnotatedWithAtStat> annotatedMembers = classesToStaticMembers.get(clazz); for (MemberAnnotatedWithAtStat annotatedMember : annotatedMembers) { Stat stat = annotatedMember.getStat(); stats.register(StatDescriptor.of( stat.value(), stat.description(), StatReaders.forStaticMember(annotatedMember.<Member>getMember()), stat.exposer())); } } public void registerAllStatsOn(Object target) { List<MemberAnnotatedWithAtStat> annotatedMembers = classesToInstanceMembers.get(target.getClass()); for (MemberAnnotatedWithAtStat annotatedMember : annotatedMembers) { Stat stat = annotatedMember.getStat(); stats.register(StatDescriptor.of( stat.value(), stat.description(), StatReaders.forMember(annotatedMember.<Member>getMember(), target), stat.exposer())); } registerStaticStatsOn(target.getClass()); } }
apache-2.0
galpha/gradoop
gradoop-data-integration/src/main/java/org/gradoop/dataintegration/transformation/functions/CreateCartesianNeighborhoodEdges.java
3274
/* * Copyright © 2014 - 2021 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.dataintegration.transformation.functions; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.functions.FunctionAnnotation; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.ResultTypeQueryable; import org.apache.flink.util.Collector; import org.gradoop.common.model.api.entities.Edge; import org.gradoop.common.model.api.entities.EdgeFactory; import org.gradoop.common.model.api.entities.Vertex; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.dataintegration.transformation.impl.NeighborhoodVertex; import java.util.List; import java.util.Objects; /** * This {@link FlatMapFunction} creates all edges between neighbor vertices. * * @param <V> The vertex type. * @param <E> The edge type. * @see org.gradoop.dataintegration.transformation.ConnectNeighbors */ @FunctionAnnotation.ReadFields({"f1"}) public class CreateCartesianNeighborhoodEdges<V extends Vertex, E extends Edge> implements FlatMapFunction<Tuple2<V, List<NeighborhoodVertex>>, E>, ResultTypeQueryable<E> { /** * The type of the edges created by the factory. */ private final Class<E> edgeType; /** * Reduce object instantiations. */ private E reuseEdge; /** * The constructor to calculate the edges in the neighborhood. * * @param factory The factory the edges are created with. * @param newEdgeLabel The label of the created edge between the neighbors. */ public CreateCartesianNeighborhoodEdges(EdgeFactory<E> factory, String newEdgeLabel) { this.edgeType = Objects.requireNonNull(factory).getType(); this.reuseEdge = factory.createEdge(Objects.requireNonNull(newEdgeLabel), GradoopId.NULL_VALUE, GradoopId.NULL_VALUE); } @Override public void flatMap(Tuple2<V, List<NeighborhoodVertex>> value, Collector<E> out) { final List<NeighborhoodVertex> neighbors = value.f1; // To "simulate" bidirectional edges we have to create an edge for each direction. for (NeighborhoodVertex source : neighbors) { // The source id is the same for the inner loop, we can keep it. reuseEdge.setSourceId(source.getNeighborId()); for (NeighborhoodVertex target : neighbors) { if (source == target) { continue; } reuseEdge.setId(GradoopId.get()); reuseEdge.setTargetId(target.getNeighborId()); out.collect(reuseEdge); } } } @Override public TypeInformation<E> getProducedType() { return TypeInformation.of(edgeType); } }
apache-2.0
magnetsystems/message-server
server/plugins/mmxmgmt/src/main/java/com/magnet/mmx/server/plugin/mmxmgmt/api/push/IOSSpecific.java
1175
/* Copyright (c) 2015 Magnet Systems, 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.magnet.mmx.server.plugin.mmxmgmt.api.push; /** */ public class IOSSpecific { private Integer badge; private boolean silent; private String category; public Integer getBadge() { return badge; } public void setBadge(Integer badge) { this.badge = badge; } public boolean isSilent() { return silent; } public void setSilent(boolean silent) { this.silent = silent; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
apache-2.0
hpehl/hal.next
app/src/main/java/org/jboss/hal/client/configuration/subsystem/elytron/ElytronSubsystemView.java
1555
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * 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 org.jboss.hal.client.configuration.subsystem.elytron; import org.jboss.hal.ballroom.form.Form; import org.jboss.hal.core.mbui.MbuiContext; import org.jboss.hal.core.mbui.MbuiViewImpl; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.spi.MbuiElement; import org.jboss.hal.spi.MbuiView; @MbuiView @SuppressWarnings("DuplicateStringLiteralInspection") public abstract class ElytronSubsystemView extends MbuiViewImpl<ElytronSubsystemPresenter> implements ElytronSubsystemPresenter.MyView { public static ElytronSubsystemView create(final MbuiContext mbuiContext) { return new Mbui_ElytronSubsystemView(mbuiContext); } @MbuiElement("elytron-global-settings-form") Form<ModelNode> form; ElytronSubsystemView(final MbuiContext mbuiContext) { super(mbuiContext); } @Override public void update(final ModelNode modelNode) { form.view(modelNode); } }
apache-2.0
nileshpatelksy/hello-pod-cast
archive/FILE/Compiler/bpwj-java-phrase/code/sjm/examples/pretty/PrettyRepetitionAssembler.java
1439
package sjm.examples.pretty; import java.util.Enumeration; import java.util.Vector; import sjm.parse.Assembler; import sjm.parse.Assembly; /* * Copyright (c) 2000 Steven J. Metsker. All Rights Reserved. * * Steve Metsker makes no representations or warranties about * the fitness of this software for any particular purpose, * including the implied warranty of merchantability. */ /** * Replace the nodes above a given "fence" object with * a new composite that holds the popped nodes as its children. * * @author Steven J. Metsker * * @version 1.0 */ public class PrettyRepetitionAssembler extends Assembler { protected String name; protected Object fence; /** * Construct an assembler that will replace the nodes above the * supplied "fence" object with a new composite that will hold * the popped nodes as its children. */ public PrettyRepetitionAssembler(String name, Object fence) { this.name = name; this.fence = fence; } /** * Replace the nodes above a given "fence" object with * a new composite that holds the popped nodes as its children. * * @param Assembly the assembly to work on */ public void workOn(Assembly a) { CompositeNode newNode = new CompositeNode(name); Vector v = elementsAbove(a, fence); Enumeration e = v.elements(); while (e.hasMoreElements()) { newNode.add((ComponentNode) e.nextElement()); } a.push(newNode); } }
apache-2.0
OptimalOrange/CoolTechnologies
app/src/main/java/com/optimalorange/cooltechnologies/network/CreateFavoriteRequest.java
4271
package com.optimalorange.cooltechnologies.network; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import org.json.JSONException; import org.json.JSONObject; import android.support.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; public class CreateFavoriteRequest extends SimpleRequest<JSONObject> { private static final int YOUKU_API_REQUEST_METHOD = Method.POST; private static final String YOUKU_API_CREATE_FAVORITE = "https://openapi.youku.com/v2/videos/favorite/create.json"; private final Map<String, String> mParams; public CreateFavoriteRequest(Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(YOUKU_API_REQUEST_METHOD, YOUKU_API_CREATE_FAVORITE, listener, errorListener); mParams = params; } @Override protected Map<String, String> getParams() throws AuthFailureError { return mParams; } @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } } public static class Builder { /** * Listener to receive the response */ private Response.Listener<JSONObject> mResponseListener; /** * Error listener, or null to ignore errors. */ @Nullable private Response.ErrorListener mErrorListener; /** 应用Key(必设) */ private String client_id; /** OAuth2授权(必设) */ private String access_token; /** 视频ID(必设) */ private String video_id; /** * 应用Key(必设参数) */ public Builder setClient_id(String client_id) { this.client_id = client_id; return this; } /** * OAuth2授权(必设参数) */ public Builder setAccess_token(String access_token) { this.access_token = access_token; return this; } /** * 视频ID(必设参数) */ public Builder setVideo_id(String video_id) { this.video_id = video_id; return this; } /** * Listener to receive the response */ public Builder setResponseListener(Response.Listener<JSONObject> responseListener) { mResponseListener = responseListener; return this; } /** * Error listener, or null to ignore errors. */ public Builder setErrorListener(@Nullable Response.ErrorListener errorListener) { mErrorListener = errorListener; return this; } public CreateFavoriteRequest build() { return new CreateFavoriteRequest(buildParams(), mResponseListener, mErrorListener); } private Map<String, String> buildParams() { Map<String, String> params = new HashMap<>(); if (client_id == null) { throw new IllegalStateException("Please set client_id before build"); } params.put("client_id", client_id); if (access_token == null) { throw new IllegalStateException("Please set access_token before build"); } params.put("access_token", access_token); if (video_id == null) { throw new IllegalStateException("Please set video_id before build"); } params.put("video_id", video_id); return params; } } }
apache-2.0
goneall/SpdxEclipsePlugin
src/org/spdx/spdxeclipse/properties/SpdxProjectPropertyPage.java
10114
/** * Copyright (c) 2015 Source Auditor Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.spdx.spdxeclipse.properties; import java.util.Arrays; import java.util.regex.Pattern; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; import org.spdx.spdxeclipse.Activator; import org.spdx.spdxeclipse.ui.CommandAddSpdxToProject; import org.spdx.spdxeclipse.ui.IncludedExcludedFilesComposite; /** * Property page for SPDX Project Properties * @author Gary O'Neall * */ public class SpdxProjectPropertyPage extends PropertyPage implements IWorkbenchPropertyPage { private String originalDocumentUrl; private String originalSpdxFileName; private String[] originalExcludedFilesPattern; private String[] origiginalIncludedDirectories; private Text txtSpdxFileName = null; private Text txtDocumentUrl = null; private IProject project = null; Pattern fileNameRegex = Pattern.compile("[_a-zA-Z0-9\\-\\.]+"); IncludedExcludedFilesComposite ieComposite = null; public SpdxProjectPropertyPage() { } @Override /** * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { project = ((IResource)(this.getElement())).getProject(); try { if (SpdxProjectProperties.isSpdxInitialized(project)) { return createInitializedComposite(parent, project); } else { // create a composite with an enable SPDX button return createUninitializedSpdxComposite(parent, project); } } catch (CoreException ex) { Composite composite = new Composite(parent, SWT.None); GridLayout layout = new GridLayout(); composite.setLayout(layout); GridData data = new GridData(GridData.FILL); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; composite.setLayoutData(data); Label lblError = new Label(composite, SWT.BORDER); Activator.getDefault().logError("Error occurred fetching property values. See log for details", ex); lblError.setText("Error occurred fetching property values. See log for details"); return composite; } } private Control createUninitializedSpdxComposite(Composite parent, final IProject project) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; composite.setLayoutData(data); final Label lblNeedToCreate = new Label(composite, SWT.NONE); lblNeedToCreate.setText("SPDX has not be added to this project"); lblNeedToCreate.setToolTipText("To enable SPDX, add SPDX to this project in the project menu\nor press the Add SPDX button"); final Button btCreateSpdx = new Button(composite, SWT.PUSH); btCreateSpdx.setText("Add SPDX"); btCreateSpdx.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { CommandAddSpdxToProject.createSpdxProject(getShell(), project.getName()); btCreateSpdx.setText("SPDX Created"); btCreateSpdx.setEnabled(false); lblNeedToCreate.setText("SPDX created - press OK to continue"); } }); return composite; } private Composite createInitializedComposite(Composite parent, IProject project) throws CoreException { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData(GridData.FILL); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; composite.setLayoutData(data); this.originalDocumentUrl = SpdxProjectProperties.getSpdxDocUrl(project); this.originalSpdxFileName = SpdxProjectProperties.getSpdxFileName(project); this.originalExcludedFilesPattern = SpdxProjectProperties.getExcludedFilePatterns(project); this.origiginalIncludedDirectories = SpdxProjectProperties.getIncludedResourceDirectories(project); Label lblSpdxFileName = new Label(composite, SWT.NONE); lblSpdxFileName.setText("SPDX File Name: "); String fileNameToolTip = "Name of the SPDX file to store the SPDX date in the root of the project folder"; lblSpdxFileName.setToolTipText(fileNameToolTip); txtSpdxFileName = new Text(composite, SWT.BORDER); GridData gdSpdxFileName = new GridData(); gdSpdxFileName.horizontalAlignment = SWT.FILL; gdSpdxFileName.grabExcessHorizontalSpace = true; txtSpdxFileName.setLayoutData(gdSpdxFileName); txtSpdxFileName.setToolTipText(fileNameToolTip); txtSpdxFileName.setText(this.originalSpdxFileName); txtSpdxFileName.addListener(SWT.Verify, new Listener() { @Override public void handleEvent(Event event) { event.doit = fileNameRegex.matcher(txtSpdxFileName.getText()).matches(); } }); Label lblDocUrl = new Label(composite, SWT.None); lblDocUrl.setText("Document URL: "); this.txtDocumentUrl = new Text(composite, SWT.NONE | SWT.READ_ONLY); String docUrlToolTip = "SPDX document URL. Note - this property can not be changed once the SPDX document is created"; lblDocUrl.setToolTipText(docUrlToolTip); this.txtDocumentUrl.setToolTipText(docUrlToolTip); this.txtDocumentUrl.setText(this.originalDocumentUrl); ieComposite = new IncludedExcludedFilesComposite(composite, SWT.NONE, project, this.origiginalIncludedDirectories, this.originalExcludedFilesPattern); GridData gdIe = new GridData(); gdIe.horizontalSpan = 2; gdIe.horizontalAlignment = SWT.FILL; gdIe.verticalAlignment = SWT.FILL; gdIe.grabExcessVerticalSpace = true; ieComposite.setLayoutData(gdIe); return composite; } @Override public void performApply() { final String newSpdxFileName = txtSpdxFileName.getText().trim(); if (!this.originalSpdxFileName.equals(newSpdxFileName)) { try { SpdxProjectProperties.setSpdxFileName(project, newSpdxFileName); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX file name: "+e.getCause().getMessage()); return; } } if (!Arrays.equals(this.origiginalIncludedDirectories, this.ieComposite.getIncludedResourcePaths())) { try { SpdxProjectProperties.setIncludedResourceDirectories(project, this.ieComposite.getIncludedResourcePaths()); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX included resource directories: "+e.getCause().getMessage()); return; } } if (!Arrays.equals(this.originalExcludedFilesPattern, this.ieComposite.getExcludeFilePatterns())) { try { SpdxProjectProperties.setExcludedFilePatterns(project, this.ieComposite.getExcludeFilePatterns()); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX excluded file patterns: "+e.getCause().getMessage()); return; } catch (InvalidExcludedFilePattern e) { MessageDialog.openError(this.getShell(), "Error", e.getCause().getMessage()); return; } } } @Override public boolean performOk() { final String newSpdxFileName = txtSpdxFileName.getText().trim(); if (!this.originalSpdxFileName.equals(newSpdxFileName)) { try { SpdxProjectProperties.setSpdxFileName(project, newSpdxFileName); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX file name: "+e.getCause().getMessage()); return false; } } if (!Arrays.equals(this.origiginalIncludedDirectories, this.ieComposite.getIncludedResourcePaths())) { try { SpdxProjectProperties.setIncludedResourceDirectories(project, this.ieComposite.getIncludedResourcePaths()); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX included resource directories: "+e.getCause().getMessage()); return false; } } if (!Arrays.equals(this.originalExcludedFilesPattern, this.ieComposite.getExcludeFilePatterns())) { try { SpdxProjectProperties.setExcludedFilePatterns(project, this.ieComposite.getExcludeFilePatterns()); } catch (CoreException e) { MessageDialog.openError(this.getShell(), "Error", "Error setting new SPDX excluded file patterns: "+e.getCause().getMessage()); return false; } catch (InvalidExcludedFilePattern e) { MessageDialog.openError(this.getShell(), "Error", e.getCause().getMessage()); return false; } } return super.performOk(); } @Override public void performDefaults() { // put back to the original this.txtSpdxFileName.setText(this.originalSpdxFileName); this.ieComposite.setExcludedPatterns(this.originalExcludedFilesPattern); this.ieComposite.setIncludedDirectories(this.origiginalIncludedDirectories); } }
apache-2.0
hjj2017/xgame-part-tmpl
src/main/java/com/game/part/util/FieldUtil.java
1574
package com.game.part.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * 类字段实用工具 * * @author hjj2017 * @since 2015/3/17 * */ public final class FieldUtil { /** * 类默认构造器 * */ private FieldUtil() { } /** * 获取泛型类型中的真实类型, * 例如 List&lt;Integer&gt; 类型, 最终会得到 Integer * * @param f * @return * */ public static Type getGenericTypeA(Field f) { if (f == null) { // 如果参数对象为空, // 则直接退出! return null; } if (!(f.getGenericType() instanceof ParameterizedType)) { // 如果不是泛型类型, // 则直接退出! return null; } // 获取泛型参数 ParameterizedType tType = (ParameterizedType)f.getGenericType(); if (tType.getActualTypeArguments().length <= 0) { // 如果泛型参数太少, // 则直接退出! return null; } return tType.getActualTypeArguments()[0]; } /** * 是否为临时的 this 指针? * * @param f * @return * */ public static boolean isTempThisPointer(Field f) { if (f == null) { return false; } else { return f.isSynthetic() && Modifier.isFinal(f.getModifiers()) && f.getName().startsWith("this$"); } } }
apache-2.0
mendix/MobileSlider
test/javasource/system/proxies/User.java
14439
// This file was generated by Mendix Business Modeler. // // WARNING: Code you write here will be lost the next time you deploy the project. package system.proxies; import com.mendix.core.Core; import com.mendix.core.CoreException; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixIdentifier; import com.mendix.systemwideinterfaces.core.IMendixObject; /** * */ public class User { private final IMendixObject userMendixObject; private final IContext context; /** * Internal name of this entity */ public static final String entityName = "System.User"; /** * Enum describing members of this entity */ public enum MemberNames { Name("Name"), Password("Password"), LastLogin("LastLogin"), Blocked("Blocked"), Active("Active"), FailedLogins("FailedLogins"), WebServiceUser("WebServiceUser"), IsAnonymous("IsAnonymous"), UserRoles("System.UserRoles"), User_Language("System.User_Language"), User_TimeZone("System.User_TimeZone"); private String metaName; MemberNames(String s) { metaName = s; } @Override public String toString() { return metaName; } } public User(IContext context) { this(context, Core.instantiate(context, "System.User")); } protected User(IContext context, IMendixObject userMendixObject) { if (userMendixObject == null) throw new IllegalArgumentException("The given object cannot be null."); if (!Core.isSubClassOf("System.User", userMendixObject.getType())) throw new IllegalArgumentException("The given object is not a System.User"); this.userMendixObject = userMendixObject; this.context = context; } /** * @deprecated Use 'User.load(IContext, IMendixIdentifier)' instead. */ @Deprecated public static system.proxies.User initialize(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException { return system.proxies.User.load(context, mendixIdentifier); } /** * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called. * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access). */ public static system.proxies.User initialize(IContext context, IMendixObject mendixObject) { if (Core.isSubClassOf("UserManagement.Account", mendixObject.getType())) return usermanagement.proxies.Account.initialize(context, mendixObject); return new system.proxies.User(context, mendixObject); } public static system.proxies.User load(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException { IMendixObject mendixObject = Core.retrieveId(context, mendixIdentifier); return system.proxies.User.initialize(context, mendixObject); } public static java.util.List<? extends system.proxies.User> load(IContext context, String xpathConstraint) throws CoreException { java.util.List<system.proxies.User> result = new java.util.ArrayList<system.proxies.User>(); for (IMendixObject obj : Core.retrieveXPathQuery(context, "//System.User" + xpathConstraint)) result.add(system.proxies.User.initialize(context, obj)); return result; } /** * Commit the changes made on this proxy object. */ public final void commit() throws CoreException { Core.commit(context, getMendixObject()); } /** * Commit the changes made on this proxy object using the specified context. */ public final void commit(IContext context) throws CoreException { Core.commit(context, getMendixObject()); } /** * Delete the object. */ public final void delete() { Core.delete(context, getMendixObject()); } /** * Delete the object using the specified context. */ public final void delete(IContext context) { Core.delete(context, getMendixObject()); } /** * @return value of Name */ public final String getName() { return getName(getContext()); } /** * @param context * @return value of Name */ public final String getName(IContext context) { return (String) getMendixObject().getValue(context, MemberNames.Name.toString()); } /** * Set value of Name * @param name */ public final void setName(String name) { setName(getContext(), name); } /** * Set value of Name * @param context * @param name */ public final void setName(IContext context, String name) { getMendixObject().setValue(context, MemberNames.Name.toString(), name); } /** * Set value of Password * @param password */ public final void setPassword(String password) { setPassword(getContext(), password); } /** * Set value of Password * @param context * @param password */ public final void setPassword(IContext context, String password) { getMendixObject().setValue(context, MemberNames.Password.toString(), password); } /** * @return value of LastLogin */ public final java.util.Date getLastLogin() { return getLastLogin(getContext()); } /** * @param context * @return value of LastLogin */ public final java.util.Date getLastLogin(IContext context) { return (java.util.Date) getMendixObject().getValue(context, MemberNames.LastLogin.toString()); } /** * Set value of LastLogin * @param lastlogin */ public final void setLastLogin(java.util.Date lastlogin) { setLastLogin(getContext(), lastlogin); } /** * Set value of LastLogin * @param context * @param lastlogin */ public final void setLastLogin(IContext context, java.util.Date lastlogin) { getMendixObject().setValue(context, MemberNames.LastLogin.toString(), lastlogin); } /** * @return value of Blocked */ public final Boolean getBlocked() { return getBlocked(getContext()); } /** * @param context * @return value of Blocked */ public final Boolean getBlocked(IContext context) { return (Boolean) getMendixObject().getValue(context, MemberNames.Blocked.toString()); } /** * Set value of Blocked * @param blocked */ public final void setBlocked(Boolean blocked) { setBlocked(getContext(), blocked); } /** * Set value of Blocked * @param context * @param blocked */ public final void setBlocked(IContext context, Boolean blocked) { getMendixObject().setValue(context, MemberNames.Blocked.toString(), blocked); } /** * @return value of Active */ public final Boolean getActive() { return getActive(getContext()); } /** * @param context * @return value of Active */ public final Boolean getActive(IContext context) { return (Boolean) getMendixObject().getValue(context, MemberNames.Active.toString()); } /** * Set value of Active * @param active */ public final void setActive(Boolean active) { setActive(getContext(), active); } /** * Set value of Active * @param context * @param active */ public final void setActive(IContext context, Boolean active) { getMendixObject().setValue(context, MemberNames.Active.toString(), active); } /** * @return value of FailedLogins */ public final Integer getFailedLogins() { return getFailedLogins(getContext()); } /** * @param context * @return value of FailedLogins */ public final Integer getFailedLogins(IContext context) { return (Integer) getMendixObject().getValue(context, MemberNames.FailedLogins.toString()); } /** * Set value of FailedLogins * @param failedlogins */ public final void setFailedLogins(Integer failedlogins) { setFailedLogins(getContext(), failedlogins); } /** * Set value of FailedLogins * @param context * @param failedlogins */ public final void setFailedLogins(IContext context, Integer failedlogins) { getMendixObject().setValue(context, MemberNames.FailedLogins.toString(), failedlogins); } /** * @return value of WebServiceUser */ public final Boolean getWebServiceUser() { return getWebServiceUser(getContext()); } /** * @param context * @return value of WebServiceUser */ public final Boolean getWebServiceUser(IContext context) { return (Boolean) getMendixObject().getValue(context, MemberNames.WebServiceUser.toString()); } /** * Set value of WebServiceUser * @param webserviceuser */ public final void setWebServiceUser(Boolean webserviceuser) { setWebServiceUser(getContext(), webserviceuser); } /** * Set value of WebServiceUser * @param context * @param webserviceuser */ public final void setWebServiceUser(IContext context, Boolean webserviceuser) { getMendixObject().setValue(context, MemberNames.WebServiceUser.toString(), webserviceuser); } /** * @return value of IsAnonymous */ public final Boolean getIsAnonymous() { return getIsAnonymous(getContext()); } /** * @param context * @return value of IsAnonymous */ public final Boolean getIsAnonymous(IContext context) { return (Boolean) getMendixObject().getValue(context, MemberNames.IsAnonymous.toString()); } /** * Set value of IsAnonymous * @param isanonymous */ public final void setIsAnonymous(Boolean isanonymous) { setIsAnonymous(getContext(), isanonymous); } /** * Set value of IsAnonymous * @param context * @param isanonymous */ public final void setIsAnonymous(IContext context, Boolean isanonymous) { getMendixObject().setValue(context, MemberNames.IsAnonymous.toString(), isanonymous); } /** * @return value of UserRoles */ public final java.util.List<system.proxies.UserRole> getUserRoles() throws CoreException { return getUserRoles(getContext()); } /** * @param context * @return value of UserRoles */ @SuppressWarnings("unchecked") public final java.util.List<system.proxies.UserRole> getUserRoles(IContext context) throws CoreException { java.util.List<system.proxies.UserRole> result = new java.util.ArrayList<system.proxies.UserRole>(); Object valueObject = getMendixObject().getValue(context, MemberNames.UserRoles.toString()); if (valueObject == null) return result; for (IMendixObject mendixObject : Core.retrieveIdList(context, (java.util.List<IMendixIdentifier>) valueObject)) result.add(system.proxies.UserRole.initialize(context, mendixObject)); return result; } /** * Set value of UserRoles * @param userroles */ public final void setUserRoles(java.util.List<system.proxies.UserRole> userroles) { setUserRoles(getContext(), userroles); } /** * Set value of UserRoles * @param context * @param userroles */ public final void setUserRoles(IContext context, java.util.List<system.proxies.UserRole> userroles) { java.util.List<IMendixIdentifier> identifiers = new java.util.ArrayList<IMendixIdentifier>(); for (system.proxies.UserRole proxyObject : userroles) identifiers.add(proxyObject.getMendixObject().getId()); getMendixObject().setValue(context, MemberNames.UserRoles.toString(), identifiers); } /** * @return value of User_Language */ public final system.proxies.Language getUser_Language() throws CoreException { return getUser_Language(getContext()); } /** * @param context * @return value of User_Language */ public final system.proxies.Language getUser_Language(IContext context) throws CoreException { system.proxies.Language result = null; IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.User_Language.toString()); if (identifier != null) result = system.proxies.Language.load(context, identifier); return result; } /** * Set value of User_Language * @param user_language */ public final void setUser_Language(system.proxies.Language user_language) { setUser_Language(getContext(), user_language); } /** * Set value of User_Language * @param context * @param user_language */ public final void setUser_Language(IContext context, system.proxies.Language user_language) { if (user_language == null) getMendixObject().setValue(context, MemberNames.User_Language.toString(), null); else getMendixObject().setValue(context, MemberNames.User_Language.toString(), user_language.getMendixObject().getId()); } /** * @return value of User_TimeZone */ public final system.proxies.TimeZone getUser_TimeZone() throws CoreException { return getUser_TimeZone(getContext()); } /** * @param context * @return value of User_TimeZone */ public final system.proxies.TimeZone getUser_TimeZone(IContext context) throws CoreException { system.proxies.TimeZone result = null; IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.User_TimeZone.toString()); if (identifier != null) result = system.proxies.TimeZone.load(context, identifier); return result; } /** * Set value of User_TimeZone * @param user_timezone */ public final void setUser_TimeZone(system.proxies.TimeZone user_timezone) { setUser_TimeZone(getContext(), user_timezone); } /** * Set value of User_TimeZone * @param context * @param user_timezone */ public final void setUser_TimeZone(IContext context, system.proxies.TimeZone user_timezone) { if (user_timezone == null) getMendixObject().setValue(context, MemberNames.User_TimeZone.toString(), null); else getMendixObject().setValue(context, MemberNames.User_TimeZone.toString(), user_timezone.getMendixObject().getId()); } /** * @return the IMendixObject instance of this proxy for use in the Core interface. */ public final IMendixObject getMendixObject() { return userMendixObject; } /** * @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization. */ public final IContext getContext() { return context; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj != null && getClass().equals(obj.getClass())) { final system.proxies.User that = (system.proxies.User) obj; return getMendixObject().equals(that.getMendixObject()); } return false; } @Override public int hashCode() { return getMendixObject().hashCode(); } /** * @return String name of this class */ public static String getType() { return "System.User"; } /** * @return String GUID from this object, format: ID_0000000000 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object. */ @Deprecated public String getGUID() { return "ID_" + getMendixObject().getId().toLong(); } }
apache-2.0
mayl8822/binnavi
src/main/java/com/google/security/zynamics/zylib/gui/JHint/JHintDialog.java
1442
// Copyright 2011-2016 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 // // 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.security.zynamics.zylib.gui.JHint; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Window; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.border.LineBorder; public class JHintDialog extends JDialog { private static final long serialVersionUID = -6233942484161880642L; public JHintDialog(final Window parent, final String message) { super(parent); setResizable(false); setLayout(new BorderLayout()); setAlwaysOnTop(true); setUndecorated(true); final JPanel innerPanel = new JPanel(new BorderLayout()); innerPanel.setBorder(new LineBorder(Color.BLACK)); final JTextArea textField = new JTextArea(message); textField.setEditable(false); innerPanel.add(textField); add(innerPanel); pack(); } }
apache-2.0
iveselovskiy/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryAdapter.java
13460
/* * 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.ignite.internal.processors.cache.query; import org.apache.ignite.*; import org.apache.ignite.cache.*; import org.apache.ignite.cache.query.*; import org.apache.ignite.cluster.*; import org.apache.ignite.internal.cluster.*; import org.apache.ignite.internal.processors.cache.*; import org.apache.ignite.internal.processors.query.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.lang.*; import org.apache.ignite.plugin.security.*; import org.jetbrains.annotations.*; import java.util.*; import static org.apache.ignite.internal.processors.cache.query.GridCacheQueryType.*; /** * Query adapter. */ public class GridCacheQueryAdapter<T> implements CacheQuery<T> { /** */ private final GridCacheContext<?, ?> cctx; /** */ private final GridCacheQueryType type; /** */ private final IgniteLogger log; /** Class name in case of portable query. */ private final String clsName; /** */ private final String clause; /** */ private final IgniteBiPredicate<Object, Object> filter; /** */ private final boolean incMeta; /** */ private volatile GridCacheQueryMetricsAdapter metrics; /** */ private volatile int pageSize = Query.DFLT_PAGE_SIZE; /** */ private volatile long timeout; /** */ private volatile boolean keepAll = true; /** */ private volatile boolean incBackups; /** */ private volatile boolean dedup; /** */ private volatile ClusterGroup prj; /** */ private boolean keepPortable; /** */ private UUID subjId; /** */ private int taskHash; /** * @param cctx Context. * @param type Query type. * @param clsName Class name. * @param clause Clause. * @param filter Scan filter. * @param incMeta Include metadata flag. * @param keepPortable Keep portable flag. */ public GridCacheQueryAdapter(GridCacheContext<?, ?> cctx, GridCacheQueryType type, @Nullable String clsName, @Nullable String clause, @Nullable IgniteBiPredicate<Object, Object> filter, boolean incMeta, boolean keepPortable) { assert cctx != null; assert type != null; this.cctx = cctx; this.type = type; this.clsName = clsName; this.clause = clause; this.filter = filter; this.incMeta = incMeta; this.keepPortable = keepPortable; log = cctx.logger(getClass()); metrics = new GridCacheQueryMetricsAdapter(); } /** * @param cctx Context. * @param type Query type. * @param log Logger. * @param pageSize Page size. * @param timeout Timeout. * @param keepAll Keep all flag. * @param incBackups Include backups flag. * @param dedup Enable dedup flag. * @param prj Grid projection. * @param filter Key-value filter. * @param clsName Class name. * @param clause Clause. * @param incMeta Include metadata flag. * @param keepPortable Keep portable flag. * @param subjId Security subject ID. * @param taskHash Task hash. */ public GridCacheQueryAdapter(GridCacheContext<?, ?> cctx, GridCacheQueryType type, IgniteLogger log, int pageSize, long timeout, boolean keepAll, boolean incBackups, boolean dedup, ClusterGroup prj, IgniteBiPredicate<Object, Object> filter, @Nullable String clsName, String clause, boolean incMeta, boolean keepPortable, UUID subjId, int taskHash) { this.cctx = cctx; this.type = type; this.log = log; this.pageSize = pageSize; this.timeout = timeout; this.keepAll = keepAll; this.incBackups = incBackups; this.dedup = dedup; this.prj = prj; this.filter = filter; this.clsName = clsName; this.clause = clause; this.incMeta = incMeta; this.keepPortable = keepPortable; this.subjId = subjId; this.taskHash = taskHash; } /** * @return Type. */ public GridCacheQueryType type() { return type; } /** * @return Class name. */ @Nullable public String queryClassName() { return clsName; } /** * @return Clause. */ @Nullable public String clause() { return clause; } /** * @return Include metadata flag. */ public boolean includeMetadata() { return incMeta; } /** * @return {@code True} if portable should not be deserialized. */ public boolean keepPortable() { return keepPortable; } /** * Forces query to keep portable object representation even if query was created on plain projection. * * @param keepPortable Keep portable flag. */ public void keepPortable(boolean keepPortable) { this.keepPortable = keepPortable; } /** * @return Security subject ID. */ public UUID subjectId() { return subjId; } /** * @return Task hash. */ public int taskHash() { return taskHash; } /** * @param subjId Security subject ID. */ public void subjectId(UUID subjId) { this.subjId = subjId; } /** {@inheritDoc} */ @Override public CacheQuery<T> pageSize(int pageSize) { A.ensure(pageSize > 0, "pageSize > 0"); this.pageSize = pageSize; return this; } /** * @return Page size. */ public int pageSize() { return pageSize; } /** {@inheritDoc} */ @Override public CacheQuery<T> timeout(long timeout) { A.ensure(timeout >= 0, "timeout >= 0"); this.timeout = timeout; return this; } /** * @return Timeout. */ public long timeout() { return timeout; } /** {@inheritDoc} */ @Override public CacheQuery<T> keepAll(boolean keepAll) { this.keepAll = keepAll; return this; } /** * @return Keep all flag. */ public boolean keepAll() { return keepAll; } /** {@inheritDoc} */ @Override public CacheQuery<T> includeBackups(boolean incBackups) { this.incBackups = incBackups; return this; } /** * @return Include backups. */ public boolean includeBackups() { return incBackups; } /** {@inheritDoc} */ @Override public CacheQuery<T> enableDedup(boolean dedup) { this.dedup = dedup; return this; } /** * @return Enable dedup flag. */ public boolean enableDedup() { return dedup; } /** {@inheritDoc} */ @Override public CacheQuery<T> projection(ClusterGroup prj) { this.prj = prj; return this; } /** * @return Grid projection. */ public ClusterGroup projection() { return prj; } /** * @return Key-value filter. */ @Nullable public <K, V> IgniteBiPredicate<K, V> scanFilter() { return (IgniteBiPredicate<K, V>)filter; } /** * @throws IgniteCheckedException If query is invalid. */ public void validate() throws IgniteCheckedException { if ((type != SCAN && type != SET) && !GridQueryProcessor.isEnabled(cctx.config())) throw new IgniteCheckedException("Indexing is disabled for cache: " + cctx.cache().name()); } /** * @param res Query result. * @param err Error or {@code null} if query executed successfully. * @param startTime Start time. * @param duration Duration. */ public void onExecuted(Object res, Throwable err, long startTime, long duration) { boolean fail = err != null; // Update own metrics. metrics.onQueryExecute(duration, fail); // Update metrics in query manager. cctx.queries().onMetricsUpdate(duration, fail); if (log.isDebugEnabled()) log.debug("Query execution finished [qry=" + this + ", startTime=" + startTime + ", duration=" + duration + ", fail=" + fail + ", res=" + res + ']'); } /** {@inheritDoc} */ @Override public CacheQueryFuture<T> execute(@Nullable Object... args) { return execute(null, null, args); } /** {@inheritDoc} */ @Override public <R> CacheQueryFuture<R> execute(IgniteReducer<T, R> rmtReducer, @Nullable Object... args) { return execute(rmtReducer, null, args); } /** {@inheritDoc} */ @Override public <R> CacheQueryFuture<R> execute(IgniteClosure<T, R> rmtTransform, @Nullable Object... args) { return execute(null, rmtTransform, args); } @Override public QueryMetrics metrics() { return metrics.copy(); } @Override public void resetMetrics() { metrics = new GridCacheQueryMetricsAdapter(); } /** * @param rmtReducer Optional reducer. * @param rmtTransform Optional transformer. * @param args Arguments. * @return Future. */ @SuppressWarnings("IfMayBeConditional") private <R> CacheQueryFuture<R> execute(@Nullable IgniteReducer<T, R> rmtReducer, @Nullable IgniteClosure<T, R> rmtTransform, @Nullable Object... args) { Collection<ClusterNode> nodes = nodes(); cctx.checkSecurity(GridSecurityPermission.CACHE_READ); if (nodes.isEmpty()) return new GridCacheQueryErrorFuture<>(cctx.kernalContext(), new ClusterGroupEmptyCheckedException()); if (log.isDebugEnabled()) log.debug("Executing query [query=" + this + ", nodes=" + nodes + ']'); if (cctx.deploymentEnabled()) { try { cctx.deploy().registerClasses(filter, rmtReducer, rmtTransform); cctx.deploy().registerClasses(args); } catch (IgniteCheckedException e) { return new GridCacheQueryErrorFuture<>(cctx.kernalContext(), e); } } if (subjId == null) subjId = cctx.localNodeId(); taskHash = cctx.kernalContext().job().currentTaskNameHash(); GridCacheQueryBean bean = new GridCacheQueryBean(this, (IgniteReducer<Object, Object>)rmtReducer, (IgniteClosure<Object, Object>)rmtTransform, args); GridCacheQueryManager qryMgr = cctx.queries(); boolean loc = nodes.size() == 1 && F.first(nodes).id().equals(cctx.localNodeId()); if (type == SQL_FIELDS || type == SPI) return (CacheQueryFuture<R>)(loc ? qryMgr.queryFieldsLocal(bean) : qryMgr.queryFieldsDistributed(bean, nodes)); else return (CacheQueryFuture<R>)(loc ? qryMgr.queryLocal(bean) : qryMgr.queryDistributed(bean, nodes)); } /** * @return Nodes to execute on. */ private Collection<ClusterNode> nodes() { CacheMode cacheMode = cctx.config().getCacheMode(); switch (cacheMode) { case LOCAL: if (prj != null) U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " + "(only local node will be queried): " + this); return Collections.singletonList(cctx.localNode()); case REPLICATED: if (prj != null) return nodes(cctx, prj); return cctx.affinityNode() ? Collections.singletonList(cctx.localNode()) : Collections.singletonList(F.rand(nodes(cctx, null))); case PARTITIONED: return nodes(cctx, prj); default: throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode); } } /** * @param cctx Cache context. * @param prj Projection (optional). * @return Collection of data nodes in provided projection (if any). */ private static Collection<ClusterNode> nodes(final GridCacheContext<?, ?> cctx, @Nullable final ClusterGroup prj) { assert cctx != null; return F.view(CU.allNodes(cctx), new P1<ClusterNode>() { @Override public boolean apply(ClusterNode n) { return cctx.discovery().cacheAffinityNode(n, cctx.name()) && (prj == null || prj.node(n.id()) != null); } }); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridCacheQueryAdapter.class, this); } }
apache-2.0
shiftconnects/android-push-manager
sample-push-server/src/main/java/com/shiftconnects/backend/push/sample/MessagingEndpoint.java
3729
/* For step-by-step instructions on connecting your Android application to this backend module, see "App Engine Backend with Google Cloud Messaging" template documentation at https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/GcmEndpoints */ package com.shiftconnects.backend.push.sample; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiNamespace; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import javax.inject.Named; import static com.shiftconnects.backend.push.sample.OfyService.ofy; /** * An endpoint to send messages to devices registered with the backend * <p/> * For more information, see * https://developers.google.com/appengine/docs/java/endpoints/ * <p/> * NOTE: This endpoint does not use any form of authorization or * authentication! If this app is deployed, anyone can access this endpoint! If * you'd like to add authentication, take a look at the documentation. */ @Api(name = "messaging", version = "v1", namespace = @ApiNamespace(ownerDomain = "sample.push.backend.shiftconnects.com", ownerName = "sample.push.backend.shiftconnects.com", packagePath = "")) public class MessagingEndpoint { private static final Logger log = Logger.getLogger(MessagingEndpoint.class.getName()); /** * Api Keys can be obtained from the google cloud console */ private static final String API_KEY = System.getProperty("gcm.api.key"); /** * Send to the first 10 devices (You can modify this to send to any number of devices or a specific device) * * @param message The message to send */ public void sendMessage(@Named("message") String message) throws IOException { if (message == null || message.trim().length() == 0) { log.warning("Not sending message because it is empty"); return; } // crop longer messages if (message.length() > 1000) { message = message.substring(0, 1000) + "[...]"; } Sender sender = new Sender(API_KEY); Message msg = new Message.Builder().addData("message", message).build(); List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list(); for (RegistrationRecord record : records) { Result result = sender.send(msg, record.getRegId(), 5); if (result.getMessageId() != null) { log.info("Message sent to " + record.getRegId()); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // if the regId changed, we have to update the datastore log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId); record.setRegId(canonicalRegId); ofy().save().entity(record).now(); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { log.warning("Registration Id " + record.getRegId() + " no longer registered with GCM, removing from datastore"); // if the device is no longer registered with Gcm, remove it from the datastore ofy().delete().entity(record).now(); } else { log.warning("Error when sending message : " + error); } } } } }
apache-2.0
adessaigne/camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/IncomingPhoneNumberMobileEndpointConfigurationConfigurer.java
2965
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.twilio; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.component.twilio.IncomingPhoneNumberMobileEndpointConfiguration; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class IncomingPhoneNumberMobileEndpointConfigurationConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.twilio.IncomingPhoneNumberMobileEndpointConfiguration target = (org.apache.camel.component.twilio.IncomingPhoneNumberMobileEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "ApiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true; case "methodname": case "MethodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "pathaccountsid": case "PathAccountSid": target.setPathAccountSid(property(camelContext, java.lang.String.class, value)); return true; case "phonenumber": case "PhoneNumber": target.setPhoneNumber(property(camelContext, com.twilio.type.PhoneNumber.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { Map<String, Object> answer = new CaseInsensitiveMap(); answer.put("ApiName", org.apache.camel.component.twilio.internal.TwilioApiName.class); answer.put("MethodName", java.lang.String.class); answer.put("PathAccountSid", java.lang.String.class); answer.put("PhoneNumber", com.twilio.type.PhoneNumber.class); return answer; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.twilio.IncomingPhoneNumberMobileEndpointConfiguration target = (org.apache.camel.component.twilio.IncomingPhoneNumberMobileEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "ApiName": return target.getApiName(); case "methodname": case "MethodName": return target.getMethodName(); case "pathaccountsid": case "PathAccountSid": return target.getPathAccountSid(); case "phonenumber": case "PhoneNumber": return target.getPhoneNumber(); default: return null; } } }
apache-2.0