code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 2010 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.api.client.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; /** * Parses class information to determine data key name/value pairs associated with the class. * * @since 1.0 * @author Yaniv Inbar */ public final class ClassInfo { private static final ThreadLocal<WeakHashMap<Class<?>, ClassInfo>> CACHE = new ThreadLocal<WeakHashMap<Class<?>, ClassInfo>>() { @Override protected WeakHashMap<Class<?>, ClassInfo> initialValue() { return new WeakHashMap<Class<?>, ClassInfo>(); } }; /** Class. */ public final Class<?> clazz; /** Map from data key name to its field information or {@code null} for none. */ private final IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap; /** * Returns the class information for the given class. * * @param clazz class or {@code null} for {@code null} result * @return class information or {@code null} for {@code null} input */ public static ClassInfo of(Class<?> clazz) { if (clazz == null) { return null; } WeakHashMap<Class<?>, ClassInfo> cache = CACHE.get(); ClassInfo classInfo = cache.get(clazz); if (classInfo == null) { classInfo = new ClassInfo(clazz); cache.put(clazz, classInfo); } return classInfo; } /** * Returns the information for the given data key name. * * @param keyName data key name or {@code null} for {@code null} result * @return field information or {@code null} for none or for {@code null} input */ public FieldInfo getFieldInfo(String keyName) { if (keyName == null) { return null; } IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap; if (keyNameToFieldInfoMap == null) { return null; } return keyNameToFieldInfoMap.get(keyName.intern()); } /** * Returns the field for the given data key name. * * @param keyName data key name or {@code null} for {@code null} result * @return field or {@code null} for none or for {@code null} input */ public Field getField(String keyName) { FieldInfo fieldInfo = getFieldInfo(keyName); return fieldInfo == null ? null : fieldInfo.field; } /** * Returns the number of data key name/value pairs associated with this data class. */ public int getKeyCount() { IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap; if (keyNameToFieldInfoMap == null) { return 0; } return keyNameToFieldInfoMap.size(); } /** Returns the data key names associated with this data class. */ public Collection<String> getKeyNames() { IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = this.keyNameToFieldInfoMap; if (keyNameToFieldInfoMap == null) { return Collections.emptySet(); } return Collections.unmodifiableSet(keyNameToFieldInfoMap.keySet()); } /** Creates a new instance of the given class using reflection. */ public static <T> T newInstance(Class<T> clazz) { T newInstance; try { newInstance = clazz.newInstance(); } catch (IllegalAccessException e) { throw handleExceptionForNewInstance(e, clazz); } catch (InstantiationException e) { throw handleExceptionForNewInstance(e, clazz); } return newInstance; } private static IllegalArgumentException handleExceptionForNewInstance( Exception e, Class<?> clazz) { StringBuilder buf = new StringBuilder("unable to create new instance of class ").append(clazz.getName()); if (Modifier.isAbstract(clazz.getModifiers())) { buf.append(" (and) because it is abstract"); } if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) { buf.append(" (and) because it is not static"); } if (!Modifier.isPublic(clazz.getModifiers())) { buf.append(" (and) because it is not public"); } else { try { clazz.getConstructor(); } catch (NoSuchMethodException e1) { buf.append(" (and) because it has no public default constructor"); } } throw new IllegalArgumentException(buf.toString(), e); } /** * Returns a new instance of the given collection class. * <p> * If a concrete collection class in the The class of the returned collection instance depends on * the input collection class as follows (first that matches): * <ul> * <li>{@code null} or {@link ArrayList} is an instance of the collection class: returns an * {@link ArrayList}</li> * <li>Concrete subclass of {@link Collection}: returns an instance of that collection class</li> * <li>{@link HashSet} is an instance of the collection class: returns a {@link HashSet}</li> * <li>{@link TreeSet} is an instance of the collection class: returns a {@link TreeSet}</li> * </ul> * * @param collectionClass collection class or {@code null} for {@link ArrayList}. * @return new collection instance */ public static Collection<Object> newCollectionInstance(Class<?> collectionClass) { if (collectionClass == null || collectionClass.isAssignableFrom(ArrayList.class)) { return new ArrayList<Object>(); } if (0 == (collectionClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE))) { @SuppressWarnings("unchecked") Collection<Object> result = (Collection<Object>) ClassInfo.newInstance(collectionClass); return result; } if (collectionClass.isAssignableFrom(HashSet.class)) { return new HashSet<Object>(); } if (collectionClass.isAssignableFrom(TreeSet.class)) { return new TreeSet<Object>(); } throw new IllegalArgumentException( "no default collection class defined for class: " + collectionClass.getName()); } /** Returns a new instance of the given map class. */ public static Map<String, Object> newMapInstance(Class<?> mapClass) { if (mapClass != null && 0 == (mapClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE))) { @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) ClassInfo.newInstance(mapClass); return result; } if (mapClass == null || mapClass.isAssignableFrom(ArrayMap.class)) { return ArrayMap.create(); } if (mapClass.isAssignableFrom(TreeMap.class)) { return new TreeMap<String, Object>(); } throw new IllegalArgumentException( "no default map class defined for class: " + mapClass.getName()); } /** * Returns the type parameter for the given field assuming it is of type collection. */ public static Class<?> getCollectionParameter(Field field) { if (field != null) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { Type[] typeArgs = ((ParameterizedType) genericType).getActualTypeArguments(); if (typeArgs.length == 1 && typeArgs[0] instanceof Class<?>) { return (Class<?>) typeArgs[0]; } } } return null; } /** * Returns the type parameter for the given field assuming it is of type map. */ public static Class<?> getMapValueParameter(Field field) { if (field != null) { return getMapValueParameter(field.getGenericType()); } return null; } /** * Returns the type parameter for the given genericType assuming it is of type map. */ public static Class<?> getMapValueParameter(Type genericType) { if (genericType instanceof ParameterizedType) { Type[] typeArgs = ((ParameterizedType) genericType).getActualTypeArguments(); if (typeArgs.length == 2 && typeArgs[1] instanceof Class<?>) { return (Class<?>) typeArgs[1]; } } return null; } private ClassInfo(Class<?> clazz) { this.clazz = clazz; // clone map from super class Class<?> superClass = clazz.getSuperclass(); IdentityHashMap<String, FieldInfo> keyNameToFieldInfoMap = new IdentityHashMap<String, FieldInfo>(); if (superClass != null) { IdentityHashMap<String, FieldInfo> superKeyNameToFieldInfoMap = ClassInfo.of(superClass).keyNameToFieldInfoMap; if (superKeyNameToFieldInfoMap != null) { keyNameToFieldInfoMap.putAll(superKeyNameToFieldInfoMap); } } Field[] fields = clazz.getDeclaredFields(); int fieldsSize = fields.length; for (int fieldsIndex = 0; fieldsIndex < fieldsSize; fieldsIndex++) { Field field = fields[fieldsIndex]; FieldInfo fieldInfo = FieldInfo.of(field); if (fieldInfo == null) { continue; } String fieldName = fieldInfo.name; FieldInfo conflictingFieldInfo = keyNameToFieldInfoMap.get(fieldName); if (conflictingFieldInfo != null) { throw new IllegalArgumentException( "two fields have the same data key name: " + field + " and " + conflictingFieldInfo.field); } keyNameToFieldInfoMap.put(fieldName, fieldInfo); } if (keyNameToFieldInfoMap.isEmpty()) { this.keyNameToFieldInfoMap = null; } else { this.keyNameToFieldInfoMap = keyNameToFieldInfoMap; } } }
Java
/* * Copyright (c) 2010 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.api.client.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * Utilities for working with key/value data. * * @since 1.0 * @author Yaniv Inbar */ public class DataUtil { /** * Returns the map to use for the given key/value data. * * @param data any key value data, represented by an object or a map, or {@code null} * @return if {@code data} is a map returns {@code data}; else if {@code data} is {@code null}, * returns an empty map; else returns {@link ReflectionMap} on the data object */ public static Map<String, Object> mapOf(Object data) { if (data == null) { return Collections.emptyMap(); } if (data instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) data; return result; } return new ReflectionMap(data); } /** * Returns a deep clone of the given key/value data, such that the result is a completely * independent copy. * <p> * Note that final fields cannot be changed and therefore their value won't be copied. * * @param data key/value data object or map to clone or {@code null} for a {@code null} return * value * @return deep clone or {@code null} for {@code null} input */ public static <T> T clone(T data) { // don't need to clone primitive if (FieldInfo.isPrimitive(data)) { return data; } T copy; if (data instanceof GenericData) { // use clone method if possible @SuppressWarnings("unchecked") T copyTmp = (T) ((GenericData) data).clone(); copy = copyTmp; } else if (data instanceof ArrayMap<?, ?>) { // use ArrayMap's clone method if possible @SuppressWarnings({"unchecked", "rawtypes"}) T copyTmp = (T) ((ArrayMap) data).clone(); copy = copyTmp; } else { // else new to use default constructor @SuppressWarnings("unchecked") T copyTmp = (T) ClassInfo.newInstance(data.getClass()); copy = copyTmp; } cloneInternal(data, copy); return copy; } static void cloneInternal(Object src, Object dest) { // TODO: support Java arrays? Class<?> srcClass = src.getClass(); if (Collection.class.isAssignableFrom(srcClass)) { @SuppressWarnings("unchecked") Collection<Object> srcCollection = (Collection<Object>) src; if (ArrayList.class.isAssignableFrom(srcClass)) { @SuppressWarnings("unchecked") ArrayList<Object> destArrayList = (ArrayList<Object>) dest; destArrayList.ensureCapacity(srcCollection.size()); } @SuppressWarnings("unchecked") Collection<Object> destCollection = (Collection<Object>) dest; for (Object srcValue : srcCollection) { destCollection.add(clone(srcValue)); } } else { boolean isGenericData = GenericData.class.isAssignableFrom(srcClass); if (isGenericData || !Map.class.isAssignableFrom(srcClass)) { ClassInfo classInfo = ClassInfo.of(srcClass); for (String fieldName : classInfo.getKeyNames()) { FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); // skip final fields if (!fieldInfo.isFinal) { // generic data already has primitive types copied by clone() if (!isGenericData || !fieldInfo.isPrimitive) { Object srcValue = fieldInfo.getValue(src); if (srcValue != null) { fieldInfo.setValue(dest, clone(srcValue)); } } } } } else if (ArrayMap.class.isAssignableFrom(srcClass)) { @SuppressWarnings("unchecked") ArrayMap<Object, Object> destMap = (ArrayMap<Object, Object>) dest; @SuppressWarnings("unchecked") ArrayMap<Object, Object> srcMap = (ArrayMap<Object, Object>) src; int size = srcMap.size(); for (int i = 0; i < size; i++) { Object srcValue = srcMap.getValue(i); if (!FieldInfo.isPrimitive(srcValue)) { destMap.set(i, clone(srcValue)); } } } else { @SuppressWarnings("unchecked") Map<String, Object> destMap = (Map<String, Object>) dest; @SuppressWarnings("unchecked") Map<String, Object> srcMap = (Map<String, Object>) src; for (Map.Entry<String, Object> srcEntry : srcMap.entrySet()) { destMap.put(srcEntry.getKey(), clone(srcEntry.getValue())); } } } } private DataUtil() { } }
Java
/* * Copyright (c) 2010 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.api.client.util; // This code was copied from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed: encodeObject, decodeToObject, // encodeFromFile, encodeFileToFile, encodeToFile, InputStream, OutputStream, // decode(String, ...), encode(ByteBuffer,...), encode3to4 not used, URL_SAFE // and ORDERED *bets, options // original class JavaDoc: /* * <p>Encodes and decodes to and from Base64 notation.</p> <p>Homepage: <a * href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> <br /> <code>byte[] myByteArray = * Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass several pieces * of information to the encoder. In the "higher level" methods such as encodeBytes( bytes, options * ) the options parameter can be used to indicate such things as first gzipping the bytes before * encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, Section 2.1, * implementations should not add line feeds unless explicitly told to do so. I've got Base64 set to * this behavior now, although earlier versions broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you might make a * call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline * characters.</p> <p>Also...</p> <code>String encoded = Base64.encodeBytes( crazyString.getBytes() * );</code> * * * * <p> Change Log: </p> <ul> <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the * value 01111111, which is an invalid base 64 character but should not throw an * ArrayIndexOutOfBoundsException either. Led to discovery of mishandling (or potential for better * handling) of other bad input characters. You should now get an IOException if you try decoding * something that has bad characters in it.</li> <li>v2.3.6 - Fixed bug when breaking lines and the * final byte of the encoded string ended in the last column; the buffer was not properly shrunk and * contained an extra (null) byte that made it into the string.</li> <li>v2.3.5 - Fixed bug in * {@code encodeFromFile} where estimated buffer size was wrong for files of size 31, 34, and 37 * bytes.</li> <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing the * Base64.OutputStream closed the Base64 encoding (by padding with equals signs) too soon. Also * added an option to suppress the automatic decoding of gzipped streams. Also added experimental * support for specifying a class loader when using the {@code decodeToObject(java.lang.String, int, * java.lang.ClassLoader)} method.</li> <li>v2.3.3 - Changed default char encoding to US-ASCII which * reduces the internal Java footprint with its CharEncoders and so forth. Fixed some javadocs that * were inconsistent. Removed imports and specified things like java.io.IOException explicitly * inline.</li> <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the * final encoded data will be so that the code doesn't have to create two output arrays: an * oversized initial one and then a final, exact-sized one. Big win when using the {@code * encodeBytesToBytes(byte[])} family of methods (and not using the gzip options which uses a * different mechanism with streams and stuff).</li> <li>v2.3.1 - Added {@code * encodeBytesToBytes(byte[], int, int, int)} and some similar helper methods to be more efficient * with memory by not returning a String but just a byte array.</li> <li>v2.3 - <strong>This is not * a drop-in replacement!</strong> This is two years of comments and bug fixes queued up and finally * executed. Thanks to everyone who sent me stuff, and I'm sorry I wasn't able to distribute your * fixes to everyone else. Much bad coding was cleaned up including throwing exceptions where * necessary instead of returning null values or something similar. Here are some changes that may * affect you: <ul> <li><em>Does not break lines, by default.</em> This is to keep in compliance * with <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> <li><em>Throws exceptions * instead of returning null values.</em> Because some operations (especially those that may permit * the GZIP option) use IO streams, there is a possiblity of an java.io.IOException being thrown. * After some discussion and thought, I've changed the behavior of the methods to throw * java.io.IOExceptions rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, it should have been done * this way to begin with.</li> <li><em>Removed all references to System.out, System.err, and the * like.</em> Shame on me. All I can say is sorry they were ever there.</li> <li><em>Throws * NullPointerExceptions and IllegalArgumentExceptions</em> as needed such as when passed arrays are * null or offsets are invalid.</li> <li>Cleaned up as much javadoc as I could to avoid any javadoc * warnings. This was especially annoying before for people who were thorough in their own projects * and then had gobs of javadoc warnings on this file.</li> </ul> <li>v2.2.1 - Fixed bug using * URL_SAFE and ORDERED encodings. Fixed bug when using very small files (~&lt; 40 bytes).</li> * <li>v2.2 - Added some helper methods for encoding/decoding directly from one file to the next. * Also added a main() method to support command line encoding/decoding from one file to the next. * Also added these Base64 dialects: <ol> <li>The default is RFC3548 format.</li> <li>Calling * Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates URL and file name friendly format * as described in Section 4 of RFC3548. http://www.faqs.org/rfcs/rfc3548.html</li> <li>Calling * Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates URL and file name friendly format * that preserves lexical ordering as described in http://www.faqs.org/qa/rfcc-1940.html</li> </ol> * Special thanks to Jim Kellerman at <a * href="http://www.powerset.com/">http://www.powerset.com/</a> for contributing the new Base64 * dialects. </li> * * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added some convenience * methods for reading and writing to and from files.</li> <li>v2.0.2 - Now specifies UTF-8 encoding * in places where the code fails on systems with other encodings (like EBCDIC).</li> <li>v2.0.1 - * Fixed an error when decoding a single byte, that is, when the encoded data was a single * byte.</li> <li>v2.0 - I got rid of methods that used booleans to set options. Now everything is * more consolidated and cleaner. The code now detects when data that's being decoded is * gzip-compressed and will decompress it automatically. Generally things are cleaner. You'll * probably have to change some method calls that you were making to support the new options format * (<tt>int</tt>s that you "OR" together).</li> <li>v1.5.1 - Fixed bug when decompressing and * decoding to a byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. Added the ability * to "suspend" encoding in the Output Stream so you can turn on and off the encoding if you need to * embed base64 data in an otherwise "normal" stream (like an XML file).</li> <li>v1.5 - Output * stream pases on flush() command but doesn't do anything itself. This helps when using GZIP * streams. Added the ability to GZip-compress objects before encoding them.</li> <li>v1.4 - Added * helper methods to read/write files.</li> <li>v1.3.6 - Fixed OutputStream.flush() so that * 'position' is reset.</li> <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in * input stream where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> </ul> * * <p> I am placing this code in the Public Domain. Do with it as you will. This software comes with * no guarantees or warranties but with plenty of well-wishing instead! Please visit <a * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically to check for updates * or to contribute improvements. </p> * * @author Robert Harder * * @author rob@iharder.net * * @version 2.3.7 */ public class Base64 { /* ******** P R I V A T E F I E L D S ******** */ /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * Translates a Base64 value to either its 6-bit reconstruction value or a negative number * indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * <p> * Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64 * bytes to <var>destination</var>. The source and destination arrays can be manipulated anywhere * along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 3 * for the <var>source</var> array or <var>destOffset</var> + 4 for the <var>destination</var> * array. The actual number of significant bytes in your array is given by <var>numSigBytes</var>. * </p> * <p> * This is the lowest level of the encoding methods with all possible parameters. * </p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0) | (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16 : 0) | (numSigBytes > 2 ? source[srcOffset + 2] << 24 >>> 24 : 0); switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f]; destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f]; destination[destOffset + 3] = ALPHABET[inBuff & 0x3f]; return destination; case 2: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f]; destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Similar to {@link #encode(byte[])} but returns a byte array instead of instantiating a String. * This is more efficient if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encode(byte[] source) { return encode(source, 0, source.length); } /** * Similar to {@link #encode(byte[], int, int)} but returns a byte array instead of instantiating * a String. This is more efficient if you're working with I/O streams and have large data sets to * encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encode(byte[] source, int off, int len) { if (source == null) { throw new NullPointerException("Cannot serialize a null array."); } // end if: null if (off < 0) { throw new IllegalArgumentException("Cannot have negative offset: " + off); } // end if: off < 0 if (len < 0) { throw new IllegalArgumentException("Cannot have length offset: " + len); } // end if: len < 0 if (off + len > source.length) { throw new IllegalArgumentException( String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); } // end if: off < 0 // Else, don't compress. Better not to use streams at all then. // int len43 = len * 4 / 3; // byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = len / 3 * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding byte[] outBuff = new byte[encLen]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { encode3to4(source, d + off, 3, outBuff, e); lineLength += 4; } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if (e <= outBuff.length - 1) { // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff, 0, finalOut, 0, e); // System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } // System.err.println("No need to resize array."); return outBuff; // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of * them) to <var>destination</var>. The source and destination arrays can be manipulated anywhere * along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 4 * for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var> * array. This method returns the actual number of bytes that were converted from the Base64 * encoding. * <p> * This is the lowest level of the decoding methods with all possible parameters. * </p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid or there is not enough * room in the array. * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Lots of error checking and exception throwing if (source == null) { throw new NullPointerException("Source array was null."); } // end if if (destination == null) { throw new NullPointerException("Destination array was null."); } // end if if (srcOffset < 0 || srcOffset + 3 >= source.length) { throw new IllegalArgumentException(String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); } // end if if (destOffset < 0 || destOffset + 2 >= destination.length) { throw new IllegalArgumentException( String .format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); } // end if // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12; destination[destOffset] = (byte) (outBuff >>> 16); return 1; } // Example: DkL= else if (source[srcOffset + 3] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[source[srcOffset + 2]] & 0xFF) << 6; destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[source[srcOffset + 2]] & 0xFF) << 6 | DECODABET[source[srcOffset + 3]] & 0xFF; destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) outBuff; return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores * GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it is * used internally as part of the decoding process. Special case: if len = 0, an empty array is * returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping), * consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode(byte[] source) throws java.io.IOException { return decode(source, 0, source.length); } /** * Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores * GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it is * used internally as part of the decoding process. Special case: if len = 0, an empty array is * returned. Still, if you need more speed and reduced memory footprint (and aren't gzipping), * consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ @SuppressWarnings("cast") public static byte[] decode(byte[] source, int off, int len) throws java.io.IOException { // Lots of error checking and exception throwing if (source == null) { throw new NullPointerException("Cannot decode null source array."); } // end if if (off < 0 || off + len > source.length) { throw new IllegalArgumentException(String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len)); } // end if if (len == 0) { return new byte[0]; } else if (len < 4) { throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len); } // end if int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[len34]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for (i = off; i < off + len; i++) { // Loop through source sbiDecode = DECODABET[source[i] & 0xFF]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if (sbiDecode >= WHITE_SPACE_ENC) { if (sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn++] = source[i]; // Save non-whitespace if (b4Posn > 3) { // Time to decode? outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if (source[i] == EQUALS_SIGN) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format("Bad Base64 input character decimal %d in array position %d", (int) source[i] & 0xFF, i)); } // end else: } // each input character byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } // end decode } // end class Base64
Java
/* * Copyright (c) 2010 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.api.client.util; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Generic data that stores all unknown data key name/value pairs. * <p> * Subclasses can declare fields for known data keys using the {@link Key} annotation. Each field * can be of any visibility (private, package private, protected, or public) and must not be static. * {@code null} unknown data key names are not allowed, but {@code null} data values are allowed. * <p> * Iteration order of the data keys is based on the sorted (ascending) key names of the declared * fields, followed by the iteration order of all of the unknown data key name/value pairs. * * @since 1.0 * @author Yaniv Inbar */ public class GenericData extends AbstractMap<String, Object> implements Cloneable { // TODO: type parameter to specify value type? private EntrySet entrySet; /** Map of unknown fields. */ public ArrayMap<String, Object> unknownFields = ArrayMap.create(); // TODO: implement more methods for faster implementation final ClassInfo classInfo = ClassInfo.of(getClass()); @Override public int size() { return classInfo.getKeyCount() + unknownFields.size(); } @Override public final Object get(Object name) { if (!(name instanceof String)) { return null; } String fieldName = (String) name; FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); if (fieldInfo != null) { return fieldInfo.getValue(this); } return unknownFields.get(fieldName); } @Override public final Object put(String name, Object value) { FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { Object oldValue = fieldInfo.getValue(this); fieldInfo.setValue(this, value); return oldValue; } return unknownFields.put(name, value); } /** * Sets the given field value (may be {@code null}) for the given field name. Any existing value * for the field will be overwritten. It may be more slightly more efficient than * {@link #put(String, Object)} because it avoids accessing the field's original value. */ public final void set(String name, Object value) { FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { fieldInfo.setValue(this, value); return; } unknownFields.put(name, value); } @Override public final void putAll(Map<? extends String, ?> map) { for (Map.Entry<? extends String, ?> entry : map.entrySet()) { set(entry.getKey(), entry.getValue()); } } @Override public final Object remove(Object name) { if (name instanceof String) { String fieldName = (String) name; FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); if (fieldInfo != null) { throw new UnsupportedOperationException(); } return unknownFields.remove(name); } return null; } @Override public Set<Map.Entry<String, Object>> entrySet() { EntrySet entrySet = this.entrySet; if (entrySet == null) { entrySet = this.entrySet = new EntrySet(); } return entrySet; } @Override public GenericData clone() { try { @SuppressWarnings("unchecked") GenericData result = (GenericData) super.clone(); result.entrySet = null; DataUtil.cloneInternal(this, result); result.unknownFields = DataUtil.clone(unknownFields); return result; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } final class EntrySet extends AbstractSet<Map.Entry<String, Object>> { @Override public Iterator<Map.Entry<String, Object>> iterator() { return new EntryIterator(); } @Override public int size() { return GenericData.this.size(); } } final class EntryIterator implements Iterator<Map.Entry<String, Object>> { private boolean startedUnknown; private final Iterator<Map.Entry<String, Object>> unknownIterator; private final ReflectionMap.EntryIterator fieldIterator; EntryIterator() { fieldIterator = new ReflectionMap.EntryIterator(classInfo, GenericData.this); unknownIterator = unknownFields.entrySet().iterator(); } public boolean hasNext() { return !startedUnknown && fieldIterator.hasNext() || unknownIterator.hasNext(); } public Map.Entry<String, Object> next() { if (!startedUnknown) { ReflectionMap.EntryIterator fieldIterator = this.fieldIterator; if (fieldIterator.hasNext()) { return fieldIterator.next(); } startedUnknown = true; } return unknownIterator.next(); } public void remove() { if (startedUnknown) { unknownIterator.remove(); } throw new UnsupportedOperationException(); } } }
Java
/* * Copyright (c) 2010 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.api.client.json; import com.google.api.client.http.HttpParser; import com.google.api.client.http.HttpResponse; import org.codehaus.jackson.JsonParser; import java.io.IOException; import java.io.InputStream; /** * Parses HTTP JSON response content into an data class of key/value pairs. * <p> * Sample usage: * * <pre> * <code> * static void setParser(HttpTransport transport) { * transport.addParser(new JsonHttpParser()); * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public class JsonHttpParser implements HttpParser { /** Content type. Default value is {@link Json#CONTENT_TYPE}. */ public String contentType = Json.CONTENT_TYPE; public final String getContentType() { return contentType; } public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException { return Json.parseAndClose(JsonHttpParser.parserForResponse(response), dataClass, null); } /** * Returns a JSON parser to use for parsing the given HTTP response. * <p> * The response content will be closed if any throwable is thrown. On success, the current token * will be the first key in the JSON object. * * @param response HTTP response * @return JSON parser * @throws IllegalArgumentException if content type is not {@link Json#CONTENT_TYPE} * @throws IOException I/O exception */ public static JsonParser parserForResponse(HttpResponse response) throws IOException { InputStream content = response.getContent(); try { JsonParser parser = Json.JSON_FACTORY.createJsonParser(content); parser.nextToken(); content = null; return parser; } finally { if (content != null) { content.close(); } } } }
Java
/* * Copyright (c) 2010 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.api.client.json; import com.google.api.client.http.HttpContent; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import java.io.IOException; import java.io.OutputStream; /** * Serializes JSON HTTP content based on the data key/value mapping object for an item. * <p> * Sample usage: * * <pre> * <code> * static void setContent(HttpRequest request, Object data) { * JsonHttpContent content = new JsonHttpContent(); * content.data = data; * request.content = content; * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public class JsonHttpContent implements HttpContent { // TODO: ability to annotate fields as only needed for POST? /** Content type. Default value is {@link Json#CONTENT_TYPE}. */ public String contentType = Json.CONTENT_TYPE; /** Key/value pair data. */ public Object data; public long getLength() { // TODO return -1; } public final String getEncoding() { return null; } public String getType() { return Json.CONTENT_TYPE; } public void writeTo(OutputStream out) throws IOException { JsonGenerator generator = Json.JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8); Json.serialize(generator, data); generator.close(); } }
Java
/* * Copyright (c) 2010 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.api.client.json; import com.google.api.client.util.GenericData; import com.google.api.client.util.Key; /** * Generic JSON data that stores all unknown key name/value pairs. * <p> * Subclasses can declare fields for known data keys using the {@link Key} annotation. Each field * can be of any visibility (private, package private, protected, or public) and must not be static. * {@code null} unknown data key names are not allowed, but {@code null} data values are allowed. * * @since 1.0 * @author Yaniv Inbar */ public class GenericJson extends GenericData implements Cloneable { @Override public String toString() { return Json.toString(this); } @Override public GenericJson clone() { return (GenericJson) super.clone(); } }
Java
/* * Copyright (c) 2010 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.api.client.json; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.DataUtil; import com.google.api.client.util.DateTime; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.GenericData; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Map; /** * JSON utilities. * * @since 1.0 * @author Yaniv Inbar */ public class Json { // TODO: investigate an alternative JSON parser, or slimmer Jackson? // or abstract out the JSON parser? // TODO: remove the feature to allow unquoted control chars when tab // escaping is fixed? // TODO: turn off INTERN_FIELD_NAMES??? /** JSON factory. */ public static final JsonFactory JSON_FACTORY = new JsonFactory().configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true).configure( JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); /** {@code "application/json"} content type. */ public static final String CONTENT_TYPE = "application/json"; /** * Returns a debug JSON string representation for the given item intended for use in * {@link Object#toString()}. * * @param item data key/value pairs * @return debug JSON string representation */ public static String toString(Object item) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { JsonGenerator generator = Json.JSON_FACTORY.createJsonGenerator(byteStream, JsonEncoding.UTF8); try { serialize(generator, item); } finally { generator.close(); } } catch (IOException e) { e.printStackTrace(new PrintStream(byteStream)); } return byteStream.toString(); } /** Serializes the given JSON value object using the given JSON generator. */ public static void serialize(JsonGenerator generator, Object value) throws IOException { if (value == null) { generator.writeNull(); } if (value instanceof String || value instanceof Long || value instanceof Double || value instanceof BigInteger || value instanceof BigDecimal) { // TODO: double: what about +- infinity? generator.writeString(value.toString()); } else if (value instanceof Boolean) { generator.writeBoolean((Boolean) value); } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) { generator.writeNumber(((Number) value).intValue()); } else if (value instanceof Float) { // TODO: what about +- infinity? generator.writeNumber((Float) value); } else if (value instanceof DateTime) { generator.writeString(((DateTime) value).toStringRfc3339()); } else if (value instanceof List<?>) { generator.writeStartArray(); @SuppressWarnings("unchecked") List<Object> listValue = (List<Object>) value; int size = listValue.size(); for (int i = 0; i < size; i++) { serialize(generator, listValue.get(i)); } generator.writeEndArray(); } else { generator.writeStartObject(); for (Map.Entry<String, Object> entry : DataUtil.mapOf(value).entrySet()) { Object fieldValue = entry.getValue(); if (fieldValue != null) { String fieldName = entry.getKey(); generator.writeFieldName(fieldName); serialize(generator, fieldValue); } } generator.writeEndObject(); } } /** * Parse a JSON Object from the given JSON parser (which is closed after parsing completes) into * the given destination class, optionally using the given parser customizer. * * @param <T> destination class type * @param parser JSON parser * @param destinationClass destination class that has a public default constructor to use to * create a new instance * @param customizeParser optional parser customizer or {@code null} for none * @return new instance of the parsed destination class * @throws IOException I/O exception */ public static <T> T parseAndClose( JsonParser parser, Class<T> destinationClass, CustomizeJsonParser customizeParser) throws IOException { T newInstance = ClassInfo.newInstance(destinationClass); parseAndClose(parser, newInstance, customizeParser); return newInstance; } /** * Skips the values of all keys in the current object until it finds the given key. * <p> * The current token will either be the {@link JsonToken#END_OBJECT} of the current object if the * key is not found, or the value of the key that was found. * * @param parser JSON parser * @param keyToFind key to find * @throws IOException I/O exception */ public static void skipToKey(JsonParser parser, String keyToFind) throws IOException { while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); parser.nextToken(); if (keyToFind.equals(key)) { break; } parser.skipChildren(); } } /** * Parse a JSON Object from the given JSON parser (which is closed after parsing completes) into * the given destination object, optionally using the given parser customizer. * * @param parser JSON parser * @param destination destination object * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static void parseAndClose( JsonParser parser, Object destination, CustomizeJsonParser customizeParser) throws IOException { try { parse(parser, destination, customizeParser); } finally { parser.close(); } } /** * Parse a JSON Object from the given JSON parser into the given destination class, optionally * using the given parser customizer. * * @param <T> destination class type * @param parser JSON parser * @param destinationClass destination class that has a public default constructor to use to * create a new instance * @param customizeParser optional parser customizer or {@code null} for none * @return new instance of the parsed destination class * @throws IOException I/O exception */ public static <T> T parse( JsonParser parser, Class<T> destinationClass, CustomizeJsonParser customizeParser) throws IOException { T newInstance = ClassInfo.newInstance(destinationClass); parse(parser, newInstance, customizeParser); return newInstance; } /** * Parse a JSON Object from the given JSON parser into the given destination object, optionally * using the given parser customizer. * * @param parser JSON parser * @param destination destination object * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static void parse( JsonParser parser, Object destination, CustomizeJsonParser customizeParser) throws IOException { Class<?> destinationClass = destination.getClass(); ClassInfo classInfo = ClassInfo.of(destinationClass); boolean isGenericData = GenericData.class.isAssignableFrom(destinationClass); if (!isGenericData && Map.class.isAssignableFrom(destinationClass)) { @SuppressWarnings("unchecked") Map<String, Object> destinationMap = (Map<String, Object>) destination; Class<?> valueClass = ClassInfo.getMapValueParameter(destinationClass.getGenericSuperclass()); parseMap(parser, destinationMap, valueClass, customizeParser); return; } while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); JsonToken curToken = parser.nextToken(); // stop at items for feeds if (customizeParser != null && customizeParser.stopAt(destination, key)) { return; } // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(key); if (fieldInfo != null) { // skip final fields if (fieldInfo.isFinal && !fieldInfo.isPrimitive) { throw new IllegalArgumentException("final array/object fields are not supported"); } Field field = fieldInfo.field; Object fieldValue = parseValue(parser, curToken, field, fieldInfo.type, destination, customizeParser); FieldInfo.setFieldValue(field, destination, fieldValue); } else if (isGenericData) { // store unknown field in generic JSON GenericData object = (GenericData) destination; object.set(key, parseValue(parser, curToken, null, null, destination, customizeParser)); } else { // unrecognized field, skip value if (customizeParser != null) { customizeParser.handleUnrecognizedKey(destination, key); } parser.skipChildren(); } } } /** * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into * the given destination collection, optionally using the given parser customizer. * * @param parser JSON parser * @param destinationCollectionClass class of destination collection (must have a public default * constructor) * @param destinationItemClass class of destination collection item (must have a public default * constructor) * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static <T> Collection<T> parseArrayAndClose(JsonParser parser, Class<?> destinationCollectionClass, Class<T> destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { try { return parseArray(parser, destinationCollectionClass, destinationItemClass, customizeParser); } finally { parser.close(); } } /** * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into * the given destination collection, optionally using the given parser customizer. * * @param parser JSON parser * @param destinationCollection destination collection * @param destinationItemClass class of destination collection item (must have a public default * constructor) * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static <T> void parseArrayAndClose(JsonParser parser, Collection<? super T> destinationCollection, Class<T> destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { try { parseArray(parser, destinationCollection, destinationItemClass, customizeParser); } finally { parser.close(); } } /** * Parse a JSON Array from the given JSON parser into the given destination collection, optionally * using the given parser customizer. * * @param parser JSON parser * @param destinationCollectionClass class of destination collection (must have a public default * constructor) * @param destinationItemClass class of destination collection item (must have a public default * constructor) * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static <T> Collection<T> parseArray(JsonParser parser, Class<?> destinationCollectionClass, Class<T> destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { @SuppressWarnings("unchecked") Collection<T> destinationCollection = (Collection<T>) ClassInfo.newCollectionInstance(destinationCollectionClass); parseArray(parser, destinationCollection, destinationItemClass, customizeParser); return destinationCollection; } /** * Parse a JSON Array from the given JSON parser into the given destination collection, optionally * using the given parser customizer. * * @param parser JSON parser * @param destinationCollection destination collection * @param destinationItemClass class of destination collection item (must have a public default * constructor) * @param customizeParser optional parser customizer or {@code null} for none * @throws IOException I/O exception */ public static <T> void parseArray(JsonParser parser, Collection<? super T> destinationCollection, Class<T> destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { JsonToken listToken; while ((listToken = parser.nextToken()) != JsonToken.END_ARRAY) { @SuppressWarnings("unchecked") T parsedValue = (T) parseValue(parser, listToken, null, destinationItemClass, destinationCollection, customizeParser); destinationCollection.add(parsedValue); } } private static void parseMap(JsonParser parser, Map<String, Object> destinationMap, Class<?> valueClass, CustomizeJsonParser customizeParser) throws IOException { while (parser.nextToken() != JsonToken.END_OBJECT) { String key = parser.getCurrentName(); JsonToken curToken = parser.nextToken(); // stop at items for feeds if (customizeParser != null && customizeParser.stopAt(destinationMap, key)) { return; } Object value = parseValue(parser, curToken, null, valueClass, destinationMap, customizeParser); destinationMap.put(key, value); } } private static Object parseValue(JsonParser parser, JsonToken token, Field field, Class<?> fieldClass, Object destination, CustomizeJsonParser customizeParser) throws IOException { switch (token) { case START_ARRAY: if (fieldClass == null || Collection.class.isAssignableFrom(fieldClass)) { // TODO: handle JSON array of JSON array Collection<Object> collectionValue = null; if (customizeParser != null && field != null) { collectionValue = customizeParser.newInstanceForArray(destination, field); } if (collectionValue == null) { collectionValue = ClassInfo.newCollectionInstance(fieldClass); } Class<?> subFieldClass = ClassInfo.getCollectionParameter(field); parseArray(parser, collectionValue, subFieldClass, customizeParser); return collectionValue; } throw new IllegalArgumentException( "expected field type that implements Collection but got " + fieldClass + " for field " + field); case START_OBJECT: Object newInstance = null; boolean isMap = fieldClass == null || Map.class.isAssignableFrom(fieldClass); if (fieldClass != null && customizeParser != null) { newInstance = customizeParser.newInstanceForObject(destination, fieldClass); } if (newInstance == null) { if (isMap) { newInstance = ClassInfo.newMapInstance(fieldClass); } else { newInstance = ClassInfo.newInstance(fieldClass); } } if (isMap && fieldClass != null) { Class<?> valueClass; if (field != null) { valueClass = ClassInfo.getMapValueParameter(field); } else { valueClass = ClassInfo.getMapValueParameter(fieldClass.getGenericSuperclass()); } if (valueClass != null) { @SuppressWarnings("unchecked") Map<String, Object> destinationMap = (Map<String, Object>) newInstance; parseMap(parser, destinationMap, valueClass, customizeParser); return newInstance; } } parse(parser, newInstance, customizeParser); return newInstance; case VALUE_TRUE: case VALUE_FALSE: if (fieldClass != null && fieldClass != Boolean.class && fieldClass != boolean.class) { throw new IllegalArgumentException( parser.getCurrentName() + ": expected type Boolean or boolean but got " + fieldClass + " for field " + field); } return token == JsonToken.VALUE_TRUE ? Boolean.TRUE : Boolean.FALSE; case VALUE_NUMBER_FLOAT: if (fieldClass != null && fieldClass != Float.class && fieldClass != float.class) { throw new IllegalArgumentException( parser.getCurrentName() + ": expected type Float or float but got " + fieldClass + " for field " + field); } return parser.getFloatValue(); case VALUE_NUMBER_INT: if (fieldClass == null || fieldClass == Integer.class || fieldClass == int.class) { return parser.getIntValue(); } if (fieldClass == Short.class || fieldClass == short.class) { return parser.getShortValue(); } if (fieldClass == Byte.class || fieldClass == byte.class) { return parser.getByteValue(); } throw new IllegalArgumentException( parser.getCurrentName() + ": expected type Integer/int/Short/short/Byte/byte but got " + fieldClass + " for field " + field); case VALUE_STRING: // TODO: "special" values like Double.POSITIVE_INFINITY? try { return FieldInfo.parsePrimitiveValue(fieldClass, parser.getText()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(parser.getCurrentName() + " for field " + field, e); } case VALUE_NULL: return null; default: throw new IllegalArgumentException( parser.getCurrentName() + ": unexpected JSON node type: " + token); } } }
Java
/* * Copyright (c) 2010 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.api.client.json; import java.lang.reflect.Field; import java.util.Collection; /** * Customizes the behavior of a JSON parser. * <p> * All methods have a default trivial implementation, so subclasses need only implement the methods * whose behavior needs customization. * * @since 1.0 * @author Yaniv Inbar */ public class CustomizeJsonParser { /** * Returns whether to stop parsing at the given key of the given context object. */ public boolean stopAt(Object context, String key) { return false; } /** * Called when the given unrecognized key is encountered in the given context object. */ public void handleUnrecognizedKey(Object context, String key) { } /** * Returns a new instance value for the given field in the given context object for a JSON array * or {@code null} for the default behavior. */ public Collection<Object> newInstanceForArray(Object context, Field field) { return null; } /** * Returns a new instance value for the given field class in the given context object for JSON * Object or {@code null} for the default behavior. */ public Object newInstanceForObject(Object context, Class<?> fieldClass) { return null; } }
Java
/* * Copyright (c) 2010 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.api.client.json.rpc2; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.CustomizeJsonParser; import com.google.api.client.json.Json; import com.google.api.client.json.JsonHttpContent; import com.google.api.client.json.JsonHttpParser; import com.google.api.client.util.Base64; import com.google.api.client.util.Strings; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParser; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collection; import java.util.List; /** * JSON-RPC 2.0 HTTP transport for RPC requests, including both singleton and batched requests. * * @since 1.0 * @author Yaniv Inbar */ public final class JsonRpcHttpTransport { /** RPC server URL. */ public GenericUrl rpcServerUrl; /** * HTTP transport to use for executing HTTP requests. By default this is an unmodified new * instance of {@link HttpTransport}. */ public HttpTransport transport = new HttpTransport(); /** * Content type header to use for requests. By default this is {@code "application/json-rpc"}. */ public String contentType = "application/json-rpc"; /** * Accept header to use for requests. By default this is {@code "application/json-rpc"}. */ public String accept = contentType; /** * Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC * request object. * <p> * You may use {@link JsonHttpParser#parserForResponse(HttpResponse) * JsonHttpParser.parserForResponse}({@link #buildPostRequest(JsonRpcRequest) execute} (request)) * to get the {@link JsonParser}, and * {@link Json#parseAndClose(JsonParser, Class, CustomizeJsonParser)} . * </p> * * @param request JSON-RPC request object * @return HTTP request */ public HttpRequest buildPostRequest(JsonRpcRequest request) { return internalExecute(request); } /** * Builds a POST HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC * request objects. * <p> * Note that the request will always use batching -- i.e. JSON array of requests -- even if there * is only one request. You may use {@link JsonHttpParser#parserForResponse(HttpResponse) * JsonHttpParser.parserForResponse}({@link #buildPostRequest(List) execute} (requests)) to get * the {@link JsonParser}, and * {@link Json#parseArrayAndClose(JsonParser, Collection, Class, CustomizeJsonParser)} . * </p> * * @param requests JSON-RPC request objects * @return HTTP request */ public HttpRequest buildPostRequest(List<JsonRpcRequest> requests) { return internalExecute(requests); } /** * Builds a GET HTTP request for the JSON-RPC requests objects specified in the given JSON-RPC * request object. * <p> * You may use {@link JsonHttpParser#parserForResponse(HttpResponse) * JsonHttpParser.parserForResponse}( {@link #buildGetRequest(JsonRpcRequest) executeUsingGet} * (request)) to get the {@link JsonParser}, and * {@link Json#parseAndClose(JsonParser, Class, CustomizeJsonParser)} . * </p> * * @param request JSON-RPC request object * @return HTTP response * @throws IOException I/O exception */ public HttpRequest buildGetRequest(JsonRpcRequest request) throws IOException { HttpTransport transport = this.transport; HttpRequest httpRequest = transport.buildGetRequest(); GenericUrl url = httpRequest.url = rpcServerUrl.clone(); url.set("method", request.method); url.set("id", request.id); // base64 encode the params ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); JsonGenerator generator = Json.JSON_FACTORY.createJsonGenerator(byteStream, JsonEncoding.UTF8); try { Json.serialize(generator, request.params); } finally { generator.close(); } url.set("params", Strings.fromBytesUtf8(Base64.encode(byteStream.toByteArray()))); return httpRequest; } private HttpRequest internalExecute(Object data) { HttpTransport transport = this.transport; HttpRequest httpRequest = transport.buildPostRequest(); httpRequest.url = rpcServerUrl; JsonHttpContent content = new JsonHttpContent(); content.contentType = contentType; httpRequest.headers.accept = accept; content.data = data; httpRequest.content = content; return httpRequest; } }
Java
/* * Copyright (c) 2010 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.api.client.json.rpc2; import com.google.api.client.util.GenericData; import com.google.api.client.util.Key; /** * JSON-RPC 2.0 request object. * * @since 1.0 * @author Yaniv Inbar */ public class JsonRpcRequest extends GenericData { /** * A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0". */ @Key public final String jsonrpc = "2.0"; /** * An identifier established by the Client that MUST contain a String or a Number. If it is not * included it is assumed to be a notification, and will not receive a response. */ @Key public Object id; /** A String containing the name of the method to be invoked. */ @Key public String method; /** * A Structured value that holds the parameter values to be used during the invocation of the * method. This member MAY be omitted. */ @Key public Object params; }
Java
/* * Copyright (c) 2010 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.api.client.apache; import org.apache.http.annotation.Immutable; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.SchemeSocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.SocketTimeoutException; /** * The default class for creating plain (unencrypted) socks sockets. * <p> * The following parameters can be used to customize the behavior of this class: * <ul> * <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li> * </ul> * * @since 1.3 * @author Valentin Haloiu */ @Immutable public class PlainSocksSocketFactory implements SchemeSocketFactory { /** * Gets the default factory. * * @return the default factory */ public static PlainSocksSocketFactory getSocketFactory() { return new PlainSocksSocketFactory(); } /** * @param params If the parameters contain values for socks.host and socks.port they are used as * the socket server. If they are not set (or set to <code>null</code>) the function simply * returns a new instance of {@link Socket} class using default constructor. * * @return the new socket */ public Socket createSocket(final HttpParams params) { Socket sock; if (params == null) { sock = new Socket(); } else { String proxyHost = (String) params.getParameter("socks.host"); Integer proxyPort = (Integer) params.getParameter("socks.port"); if (proxyHost != null && proxyPort != null) { InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); sock = new Socket(proxy); } else { sock = new Socket(); } } return sock; } public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : createSocket(params); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int timeout = HttpConnectionParams.getConnectionTimeout(params); try { sock.connect(remoteAddress, timeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } return sock; } /** * Checks whether a socket connection is secure. This factory creates plain socks socket * connections which are not considered secure. * * @param sock the connected socket * * @return <code>false</code> * * @throws IllegalArgumentException if the argument is invalid */ public final boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This check is performed last since it calls a method implemented // by the argument object. getClass() is final in java.lang.Object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return false; } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import com.google.api.client.http.HttpContent; import org.apache.http.entity.AbstractHttpEntity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author Yaniv Inbar */ final class ContentEntity extends AbstractHttpEntity { private final long contentLength; private final HttpContent content; ContentEntity(long contentLength, HttpContent content) { this.contentLength = contentLength; this.content = content; } public InputStream getContent() { throw new UnsupportedOperationException(); } public long getContentLength() { return contentLength; } public boolean isRepeatable() { return false; } public boolean isStreaming() { return true; } public void writeTo(OutputStream out) throws IOException { content.writeTo(out); } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import com.google.api.client.http.HttpContent; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpRequestBase; import java.io.IOException; /** * @author Yaniv Inbar */ final class ApacheHttpRequest extends LowLevelHttpRequest { private final HttpClient httpClient; private final HttpRequestBase request; ApacheHttpRequest(HttpClient httpClient, HttpRequestBase request) { this.httpClient = httpClient; this.request = request; } @Override public void addHeader(String name, String value) { request.addHeader(name, value); } @Override public LowLevelHttpResponse execute() throws IOException { return new ApacheHttpResponse(httpClient.execute(request)); } @Override public void setContent(HttpContent content) throws IOException { ContentEntity entity = new ContentEntity(content.getLength(), content); entity.setContentEncoding(content.getEncoding()); entity.setContentType(content.getType()); ((HttpEntityEnclosingRequest) request).setEntity(entity); } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import com.google.api.client.http.LowLevelHttpResponse; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import java.io.IOException; import java.io.InputStream; final class ApacheHttpResponse extends LowLevelHttpResponse { private final org.apache.http.HttpResponse response; private final Header[] allHeaders; ApacheHttpResponse(org.apache.http.HttpResponse response) { this.response = response; allHeaders = response.getAllHeaders(); } @Override public int getStatusCode() { StatusLine statusLine = response.getStatusLine(); return statusLine == null ? 0 : statusLine.getStatusCode(); } @Override public InputStream getContent() throws IOException { HttpEntity entity = response.getEntity(); return entity == null ? null : entity.getContent(); } @Override public String getContentEncoding() { HttpEntity entity = response.getEntity(); if (entity != null) { Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { return contentEncodingHeader.getValue(); } } return null; } @Override public long getContentLength() { HttpEntity entity = response.getEntity(); return entity == null ? -1 : entity.getContentLength(); } @Override public String getContentType() { HttpEntity entity = response.getEntity(); if (entity != null) { Header contentTypeHeader = entity.getContentType(); if (contentTypeHeader != null) { return contentTypeHeader.getValue(); } } return null; } @Override public String getReasonPhrase() { StatusLine statusLine = response.getStatusLine(); return statusLine == null ? null : statusLine.getReasonPhrase(); } @Override public String getStatusLine() { StatusLine statusLine = response.getStatusLine(); return statusLine == null ? null : statusLine.toString(); } public String getHeaderValue(String name) { return response.getLastHeader(name).getValue(); } @Override public int getHeaderCount() { return allHeaders.length; } @Override public String getHeaderName(int index) { return allHeaders[index].getName(); } @Override public String getHeaderValue(int index) { return allHeaders[index].getValue(); } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import java.net.URI; final class HttpPatch extends HttpEntityEnclosingRequestBase { public HttpPatch(String uri) { setURI(URI.create(uri)); } @Override public String getMethod() { return "PATCH"; } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import org.apache.http.conn.ssl.TrustStrategy; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; class TrustManagerDecorator implements X509TrustManager { private final X509TrustManager trustManager; private final TrustStrategy trustStrategy; TrustManagerDecorator(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { super(); this.trustManager = trustManager; this.trustStrategy = trustStrategy; } public void checkClientTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { this.trustManager.checkClientTrusted(chain, authType); } public void checkServerTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { if (!this.trustStrategy.isTrusted(chain, authType)) { this.trustManager.checkServerTrusted(chain, authType); } } public X509Certificate[] getAcceptedIssuers() { return this.trustManager.getAcceptedIssuers(); } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import org.apache.http.annotation.ThreadSafe; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSchemeSocketFactory; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.conn.ssl.StrictHostnameVerifier; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; @ThreadSafe public class SSLSocksSocketFactory implements LayeredSchemeSocketFactory { public static final String TLS = "TLS"; public static final String SSL = "SSL"; public static final String SSLV2 = "SSLv2"; public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER = new BrowserCompatHostnameVerifier(); public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER = new StrictHostnameVerifier(); /** * Gets the default factory, which uses the default JVM settings for secure connections. * * @return the default factory */ public static SSLSocksSocketFactory getSocketFactory() { return new SSLSocksSocketFactory(); } private final javax.net.ssl.SSLSocketFactory socketfactory; private final X509HostnameVerifier hostnameVerifier; private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (algorithm == null) { algorithm = TLS; } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(truststore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); if (trustmanagers != null && trustStrategy != null) { for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; if (tm instanceof X509TrustManager) { trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy); } } } SSLContext sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); return sslcontext; } private static SSLContext createDefaultSSLContext() { try { return createSSLContext(TLS, null, null, null, null, null); } catch (Exception ex) { throw new IllegalStateException("Failure initializing default SSL context", ex); } } public SSLSocksSocketFactory(final SSLContext sslContext) { this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } public SSLSocksSocketFactory(final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) { super(); this.socketfactory = sslContext.getSocketFactory(); this.hostnameVerifier = hostnameVerifier; } private SSLSocksSocketFactory() { this(createDefaultSSLContext()); } /** * @param params If the parameters contain values for socks.host and socks.port they are used as * the socket server. If the values are not set (or set to <code>null</code>) the function * simply returns a new instance of {@link Socket} class using default constructor. * * @return the new socket */ public Socket createSocket(final HttpParams params) { Socket sock; if (params == null) { sock = new Socket(); } else { String proxyHost = (String) params.getParameter("socks.host"); Integer proxyPort = (Integer) params.getParameter("socks.port"); if (proxyHost != null && proxyPort != null) { InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); sock = new Socket(proxy); } else { sock = new Socket(); } } return sock; } public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock = socket != null ? socket : createSocket(params); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } sock.setSoTimeout(soTimeout); SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { sslsock = (SSLSocket) this.socketfactory.createSocket(sock, remoteAddress.getHostName(), remoteAddress.getPort(), true); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /* ignore */ } throw iox; } } return sslsock; } /** * Checks whether a socket connection is secure. This factory creates TLS/SSL socket connections * which, by default, are considered secure. <br/> * Derived classes may override this method to perform runtime checks, for example based on the * cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(final Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null"); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory"); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed"); } return true; } public Socket createLayeredSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose); if (this.hostnameVerifier != null) { this.hostnameVerifier.verify(host, sslSocket); } // verifyHostName() didn't blowup - good! return sslSocket; } public X509HostnameVerifier getHostnameVerifier() { return this.hostnameVerifier; } }
Java
/* * Copyright (c) 2010 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.api.client.apache; import com.google.api.client.http.LowLevelHttpTransport; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.params.ClientPNames; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.net.Proxy; /** * HTTP low-level transport based on the Apache HTTP Client library. * <p> * Default settings: * </p> * <ul> * <li>The client connection manager is set to {@link ThreadSafeClientConnManager}.</li> * <li>Timeout is set to 20 seconds using {@link HttpConnectionParams#setConnectionTimeout} and * {@link HttpConnectionParams#setSoTimeout}.</li> * <li>The socket buffer size is set to 8192 using {@link HttpConnectionParams#setSocketBufferSize}. * </li> * </ul> * <p> * These parameters may be overridden by setting the values on the {@link #httpClient}. * {@link HttpClient#getParams() getParams()}. Please read the <a * href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html">Apache HTTP * Client connection management tutorial</a> for more complex configuration questions, such as how * to set up an HTTP proxy. * </p> * * @since 1.0 * @author Yaniv Inbar */ public final class ApacheHttpTransport extends LowLevelHttpTransport { /** * Apache HTTP client. * * @since 1.1 */ public final HttpClient httpClient; /** * Singleton instance of this transport. * <p> * Sample usage: * * <pre><code>HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);</code></pre> * </p> */ public static final ApacheHttpTransport INSTANCE = new ApacheHttpTransport(); ApacheHttpTransport() { // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpParams params = new BasicHttpParams(); HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e596 SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocksSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, SSLSocksSocketFactory.getSocketFactory())); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(registry); httpClient = new DefaultHttpClient(connectionManager, params); } @Override public boolean supportsHead() { return true; } @Override public boolean supportsPatch() { return true; } @Override public boolean supportsProxy() { return true; } @Override public ApacheHttpRequest buildDeleteRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpDelete(url)); } @Override public ApacheHttpRequest buildGetRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpGet(url)); } @Override public ApacheHttpRequest buildHeadRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpHead(url)); } @Override public ApacheHttpRequest buildPatchRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpPatch(url)); } @Override public ApacheHttpRequest buildPostRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpPost(url)); } @Override public ApacheHttpRequest buildPutRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpPut(url)); } @Override public void setProxy(String host, int port, Proxy.Type type) { if (type.equals(Proxy.Type.HTTP)) { HttpHost proxy = new HttpHost(host, port, "http"); this.httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else if (type.equals(Proxy.Type.SOCKS)) { this.httpClient.getParams().setParameter("socks.host", host); this.httpClient.getParams().setParameter("socks.port", port); } } @Override public void removeProxy() { this.httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); this.httpClient.getParams().removeParameter("socks.host"); this.httpClient.getParams().removeParameter("socks.port"); } }
Java
/* * Copyright (C) 2007 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.api.client.repackaged.com.google.common.base; /** * Helper functions that can operate on any {@code Object}. * * @author Laurence Gonsalves * @since 2 (imported from Google Collections Library) */ public final class Objects { private Objects() { } /** * Determines whether two possibly-null objects are equal. Returns: * * <ul> * <li>{@code true} if {@code a} and {@code b} are both null. * <li>{@code true} if {@code a} and {@code b} are both non-null and they are equal according to * {@link Object#equals(Object)}. * <li>{@code false} in all other situations. * </ul> * * <p> * This assumes that any non-null objects passed to this function conform to the {@code equals()} * contract. */ public static boolean equal(Object a, Object b) { return a == b || a != null && a.equals(b); } }
Java
/* * Copyright (C) 2007 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.api.client.repackaged.com.google.common.base; import java.util.NoSuchElementException; /** * Simple static methods to be called at the start of your own methods to verify correct arguments * and state. This allows constructs such as * * <pre> * if (count <= 0) { * throw new IllegalArgumentException("must be positive: " + count); * }</pre> * * to be replaced with the more compact * * <pre> * checkArgument(count > 0, "must be positive: %s", count);</pre> * * Note that the sense of the expression is inverted; with {@code Preconditions} you declare what * you expect to be <i>true</i>, just as you do with an <a * href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html"> {@code assert}</a> or a * JUnit {@code assertTrue} call. * * <p> * <b>Warning:</b> only the {@code "%s"} specifier is recognized as a placeholder in these messages, * not the full range of {@link String#format(String, Object[])} specifiers. * * <p> * Take care not to confuse precondition checking with other similar types of checks! Precondition * exceptions -- including those provided here, but also {@link IndexOutOfBoundsException}, * {@link NoSuchElementException}, {@link UnsupportedOperationException} and others -- are used to * signal that the <i>calling method</i> has made an error. This tells the caller that it should not * have invoked the method when it did, with the arguments it did, or perhaps ever. Postcondition or * other invariant failures should not throw these types of exceptions. * * @author Kevin Bourrillion * @since 2 (imported from Google Collections Library) */ public final class Preconditions { private Preconditions() { } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkArgument( boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression, Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkState( boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull( T reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } return reference; } /* * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { throw new BadException(messageExpression); } * * refactored so that messageExpression is moved to a separate String-returning method. * * if (guardExpression) { throw new BadException(badMsg(...)); } * * The alternative natural refactorings into void or Exception-returning methods are much slower. * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is * a hotspot optimizer bug, which should be fixed, but that's a separate, big project). * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a * RangeCheckMicroBenchmark in the JDK that was used to test this. * * But the methods in this class want to throw different exceptions, depending on the args, so it * appears that this pattern is not directly applicable. But we can use the ridiculous, devious * trick of throwing an exception in the middle of the construction of another exception. Hotspot * is fine with that. */ /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); } return index; } private static String badElementIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index >= size return format("%s (%s) must be less than size (%s)", desc, index, size); } } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return format("%s (%s) must not be greater than size (%s)", desc, index, size); } } /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * * @param start a user-supplied index identifying a starting position in an array, list or string * @param end a user-supplied index identifying a ending position in an array, list or string * @param size the size of that array, list or string * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size}, * or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) if (start < 0 || end < start || end > size) { throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); } } private static String badPositionIndexes(int start, int end, int size) { if (start < 0 || start > size) { return badPositionIndex(start, size, "start index"); } if (end < 0 || end > size) { return badPositionIndex(end, size, "end index"); } // end < start return format("end index (%s) must not be less than start index (%s)", end, start); } /** * Substitutes each {@code %s} in {@code template} with an argument. These are matched by position * - the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than * placeholders, the unmatched arguments will be appended to the end of the formatted message in * square braces. * * @param template a non-null string containing 0 or more {@code %s} placeholders. * @param args the arguments to be substituted into the message template. Arguments are converted * to strings using {@link String#valueOf(Object)}. Arguments can be null. */ static String format(String template, Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append("]"); } return builder.toString(); } }
Java
package insight.web.delegates; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; public class ReflectionDelegate { public static <T extends Annotation> Field[] getAnnotatedFields( Class<?> clazz, Class<T> annotClass) { ArrayList<Field> fields = new ArrayList<Field>(); for (Field field : clazz.getDeclaredFields()) { if (field.getAnnotation(annotClass) != null) { fields.add(field); } } return fields.toArray(new Field[fields.size()]); } public static Method getSetterMethod(Field field) { Method[] methods = field.getDeclaringClass().getMethods(); System.out.println("Found " + methods.length + " method(s)."); for (Method method : methods) { System.out.println("Checking method " + method.getName()); if (Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(field.getType()) && method.getName().equalsIgnoreCase("set" + field.getName())) { return method; } } return null; } }
Java
package insight.web.delegates; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; /** * * AjaxJSONDelegate class set json object in HttpServletResponse and send back * to the UI. * */ public class AjaxJSONDelegate { /** * * @param jarray * holds the response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONArray jarray, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jarray.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param content * holds the response values * @param res * is HttpServletResonse. */ public static void setTextResponse(final String content, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(content); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param jsonStringer * holds response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONStringer jsonStringer, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jsonStringer.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void setResponse(final JSONObject obj, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); // System.out.print(obj.toString()); w.write(obj.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param response * @param message * @param errorData */ public static void reportError(HttpServletResponse response, String message, JSONObject errorData) { JSONObject returnObj = new JSONObject(); try { returnObj.put("success", false).put("error", message); if (errorData != null) returnObj.put("errorData", errorData); } catch (JSONException e) { e.printStackTrace(); } AjaxJSONDelegate.setResponse(returnObj, response); } }
Java
package insight.web.delegates; import insight.common.PropertyLoader; import insight.miescor.annotations.Code; import insight.miescor.annotations.Constants; import insight.miescor.annotations.Notebook; import insight.miescor.annotations.UDF; import insight.miescor.opp.domain.CodeValue; import insight.miescor.opp.domain.ICurrency; import insight.miescor.opp.domain.ILocation; import insight.miescor.opp.domain.Opportunity; import insight.miescor.opp.domain.Opportunity.ContractVal; import insight.miescor.opp.domain.Review; import insight.miescor.opp.domain.Roles; import insight.primavera.common.P6helper; import insight.primavera.common.Utils; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import com.primavera.ServerException; import com.primavera.common.value.Cost; import com.primavera.common.value.EndDate; import com.primavera.common.value.MultipartObjectIdException; import com.primavera.common.value.ObjectId; import com.primavera.integration.client.EnterpriseLoadManager; import com.primavera.integration.client.GlobalObjectManager; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BOIterator; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.enm.ProjectStatus; import com.primavera.integration.client.bo.enm.SummaryLevel; import com.primavera.integration.client.bo.enm.UDFDataType; import com.primavera.integration.client.bo.enm.UDFSubjectArea; import com.primavera.integration.client.bo.object.Currency; import com.primavera.integration.client.bo.object.EPS; import com.primavera.integration.client.bo.object.Location; import com.primavera.integration.client.bo.object.NotebookTopic; import com.primavera.integration.client.bo.object.OBS; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.client.bo.object.ProjectCode; import com.primavera.integration.client.bo.object.ProjectCodeAssignment; import com.primavera.integration.client.bo.object.ProjectCodeType; import com.primavera.integration.client.bo.object.ProjectNote; import com.primavera.integration.client.bo.object.ProjectResource; import com.primavera.integration.client.bo.object.ProjectResourceQuantity; import com.primavera.integration.client.bo.object.Resource; import com.primavera.integration.client.bo.object.ResourceAssignment; import com.primavera.integration.client.bo.object.UDFValue; import com.primavera.integration.client.bo.object.User; import com.primavera.integration.client.bo.object.UserOBS; import com.primavera.integration.network.NetworkException; public class PrimaveraDelegate { public static class ProjectTeam { private double units; private String resName; private String resType; private String resId; private String roleName; public ProjectTeam(ResourceAssignment resAsg) throws BusinessObjectException { this.units = resAsg.getPlannedUnits().doubleValue(); this.resName = resAsg.getResourceName(); this.resId = resAsg.getResourceId(); this.resType = resAsg.getResourceType().getValue(); this.roleName = resAsg.getRoleName(); } public ProjectTeam(Resource res, String roleName) throws BusinessObjectException { this.resName = res.getName(); this.resId = res.getId(); this.resType = res.getResourceType().getValue(); this.roleName = roleName; } public void append(double units) throws BusinessObjectException { this.units += units; } public String getKey() { return roleName != null ? resId + "-" + roleName : resId; } public double getUnits() { return units; } public void setUnits(double units) { this.units = units; } public String getResName() { return resName; } public void setResName(String resName) { this.resName = resName; } public String getResType() { return resType; } public void setResType(String resType) { this.resType = resType; } public String getResId() { return resId; } public void setResId(String resId) { this.resId = resId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } } private static final String NEW_OPP_EPS = PropertyLoader.getProperty( "opportunity.new.epsid", "UR"); private static final String PROPOSAL_EPS = PropertyLoader.getProperty( "opportunity.proposal.epsid", "PRP"); private static final String ESTIMATION_EPS = PropertyLoader.getProperty( "opportunity.estimation.epsid", "EST"); private static final String ARCHIVED_EPS = PropertyLoader.getProperty( "archived.opportunity.epsid", "OARCH"); private static final String PROPOSAL_OBSName = PropertyLoader.getProperty( "opportunity.proposalmanagers.obs", "Proposal Managers"); private static final String OBS_ESTIMATIONS = "Estimations"; public static void main(String[] args) { try { System.setProperty("primavera.bootstrap.home", System.getProperty( "primavera.bootstrap.home", "D:/OracleApps/Primavera/R83/p6")); P6helper helper = new P6helper(); Session session = helper.getSession(); Project project = helper.getProjectById("CORP00384"); System.out.println(project.getName()); System.out.println(setProjectNotebookContent(session, project, "Test", "<p> Test<strong>ing</strong><p>", true, true)); } catch (Exception ex) { } } public static Map<String, String> getAllUsers(Session session) throws BusinessObjectException, ServerException, NetworkException { BOIterator<User> userList = session.getEnterpriseLoadManager() .loadUsers(new String[] { "Name", "PersonalName" }, null, "Name asc"); Map<String, String> userMap = new HashMap<String, String>(); while (userList.hasNext()) { User user = userList.next(); userMap.put(user.getName(), user.getPersonalName()); } return userMap; } public static double conCurrencyVal(Session session, double value, String currencyCode) throws BusinessObjectException, ServerException, NetworkException { ICurrency currency = loadICurrency(session, currencyCode); if (currency != null && !currency.isBase()) { return currency.convert(value); } return value; } public static List<ICurrency> loadCurrencyList(Session session) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<Currency> currencyItr = elm.loadCurrencies(ICurrency.Fields, null, null); List<ICurrency> list = new ArrayList<ICurrency>(); while (currencyItr.hasNext()) { list.add(new ICurrency(currencyItr.next())); } return list; } public static ICurrency loadICurrency(Session session, String currencyId) throws BusinessObjectException, ServerException, NetworkException { Currency currency = loadCurrency(session, currencyId); return currency != null ? new ICurrency(currency) : null; } public static Currency loadCurrency(Session session, String currencyId) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<Currency> currencyItr = elm.loadCurrencies(ICurrency.Fields, "Id='" + currencyId + "'", null); if (currencyItr.hasNext()) { return currencyItr.next(); } return null; } public static List<ProjectTeam> loadProjectTeam(Session session, Project project) throws BusinessObjectException, ServerException, NetworkException { HashMap<String, ProjectTeam> mapTeam = new HashMap<String, ProjectTeam>(); if (project.getSummaryLevel().equals(SummaryLevel.WBSLEVEL)) { String[] prjResFields = new String[] { "RoleName" }; String[] resFields = new String[] { "Name", "Id", "ResourceType" }; String[] resQtyFileds = new String[] { "Quantity" }; BOIterator<ProjectResource> resItr = project .loadProjectLevelResources(prjResFields, null, null); while (resItr.hasNext()) { ProjectResource prjRes = resItr.next(); if(prjRes != null){ Resource res = prjRes.loadResource(resFields); ProjectTeam prjTeam = mapTeam .get(prjRes.getRoleName() != null ? res.getId() + "-" + prjRes.getRoleName() : res.getId()); if (prjTeam == null) { prjTeam = new ProjectTeam(res, prjRes.getRoleName()); mapTeam.put(prjTeam.getKey(), prjTeam); } BOIterator<ProjectResourceQuantity> resQtyItr = prjRes .loadProjectResourceQuantities(resQtyFileds, null, null); while (resQtyItr.hasNext()) { prjTeam.append(resQtyItr.next().getQuantity().doubleValue()); } } } } else { String[] resAsgFields = new String[] { "ResourceName", "ResourceId", "PlannedUnits", "RoleName", "ResourceType" }; BOIterator<ResourceAssignment> resAsgItr = project .loadAllResourceAssignments(resAsgFields, null, null); while (resAsgItr.hasNext()) { ResourceAssignment resAsg = resAsgItr.next(); ProjectTeam prjTeam = mapTeam .get(resAsg.getRoleName() != null ? resAsg .getResourceId() + "-" + resAsg.getRoleName() : resAsg.getResourceId()); if (prjTeam == null) { prjTeam = new ProjectTeam(resAsg); mapTeam.put(prjTeam.getKey(), prjTeam); } else { prjTeam.append(resAsg.getPlannedUnits().doubleValue()); } } } return new ArrayList<ProjectTeam>(mapTeam.values()); } public static List<ILocation> loadLocationList(Session session) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<Location> locationItr = elm.loadLocations(ILocation.Fields, null, null); List<ILocation> list = new ArrayList<ILocation>(); while (locationItr.hasNext()) { list.add(new ILocation(locationItr.next())); } Collections.sort(list, new ILocation.ILocationSort()); return list; } public static boolean setProjectNotebookContent(Session session, ObjectId projectId, String notebook, String content, boolean append, boolean extend) { try { Project project = Project.load(session, new String[] { "Id" }, projectId); if (project != null) return setProjectNotebookContent(session, project, notebook, content, append, extend); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean setProjectNotebookContent(Session session, ObjectId projectId, String notebook, String content) { return setProjectNotebookContent(session, projectId, notebook, content, false, false); } public static boolean setProjectNotebookContent(Session session, Project project, String notebook, String content) { return setProjectNotebookContent(session, project, notebook, content, false, false); } public static boolean setProjectNotebookContent(Session session, Project project, String notebook, String content, boolean append, boolean extend) { try { content = (content == null ? "" : content); BOIterator<ProjectNote> noteItr = project.loadAllProjectNotes( ProjectNote.getAllFields(), "NotebookTopicName='" + notebook + "'", null); if (noteItr.hasNext()) { ProjectNote pNote = noteItr.next(); pNote.setNote(append ? pNote.getNote() + "<br>" + content : content); pNote.update(); return true; } else { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<NotebookTopic> topicTypeItr = elm .loadNotebookTopics(new String[] { "Name", "AvailableForProject" }, "Name='" + notebook + "'", null); if (topicTypeItr.hasNext()) { NotebookTopic topicType = topicTypeItr.next(); if (topicType.getAvailableForProject()) { ObjectId typeId = topicType.getObjectId(); ProjectNote note = new ProjectNote(session); note.setNotebookTopicObjectId(typeId); note.setProjectObjectId(project.getObjectId()); note.setNote(content); note.create(); return true; } else if (extend) { topicType.setAvailableForProject(true); ObjectId typeId = topicType.getObjectId(); topicType.update(); ProjectNote note = new ProjectNote(session); note.setNotebookTopicObjectId(typeId); note.setProjectObjectId(project.getObjectId()); note.setNote(content); note.create(); return true; } else { return false; } } else if (extend) { NotebookTopic topicType = new NotebookTopic(session); topicType.setName(notebook); topicType.setAvailableForProject(true); ObjectId typeId = topicType.create(); ProjectNote note = new ProjectNote(session); note.setNotebookTopicObjectId(typeId); note.setProjectObjectId(project.getObjectId()); note.setNote(content); note.create(); return true; } else { return false; } } } catch (Exception e) { e.printStackTrace(); return false; } } public static String getProjectNotebookContent(Session session, ObjectId projectId, String notebook) { try { Project project = Project.load(session, new String[] { "Id" }, projectId); if (project != null) return getProjectNotebookContent(session, project, notebook); } catch (Exception e) { e.printStackTrace(); } return ""; } public static String getProjectNotebookContent(Session session, Project project, String notebook) { try { BOIterator<ProjectNote> noteItr = project.loadAllProjectNotes( ProjectNote.getAllFields(), "NotebookTopicName='" + notebook + "'", null); if (noteItr.hasNext()) { return noteItr.next().getNote(); } } catch (Exception e) { e.printStackTrace(); } return ""; } public static String getCodeName(Session session, ObjectId objectId) { ProjectCode code; try { code = ProjectCode.load(session, new String[] { "CodeValue" }, objectId); if (code != null) { return code.getCodeValue(); } } catch (Exception e) { e.printStackTrace(); } return null; } public static void saveOpportunity(Session session, Opportunity opportunity, String userName) throws Exception { Project project = createProject(session, opportunity); PrimaveraDelegate.assignProjectCode(session, project, PropertyLoader .getProperty("project.opportunity.projectcategory", "Opportunity")); saveDataToP6(session, project, opportunity, userName); for (ContractVal contractVal : opportunity.getContractVal()) { setProjectNotebookContent(session, project, Constants.ProjectFields.NOTEBOOK_CONTRACT_VALUE, contractVal.getValue() + " " + contractVal.getCurrency() + "</br>", true, true); } Cost contractValue = computeContractValue(session, opportunity.getContractVal()); ObjectId projObjId = project.getObjectId(); setUDFValueCost(session, UDFSubjectArea.PROJECT, Constants.ProjectFields.UDF_CONTRACT_VALUE, projObjId, contractValue); } private static Cost computeContractValue(Session session, List<ContractVal> list) { double contractValDbl = 0; for (ContractVal valueObj : list) { try { contractValDbl += loadICurrency(session, valueObj.getCurrency()) .convert( Double.parseDouble(valueObj.getValue().replace( ",", ""))); } catch (Exception e) { e.printStackTrace(); } } return new Cost(contractValDbl); } public static void setUDFValueCost(Session session, UDFSubjectArea subjectArea, String title, ObjectId objectId, Cost cost) throws BusinessObjectException, ServerException, NetworkException, MultipartObjectIdException { ObjectId udfId = Utils.getUDFTypeObjectId(subjectArea, UDFDataType.COST, title, session); String fields[] = { "CodeValue", "ForeignObjectId", "UDFTypeObjectId", "Text" }; String where = (new StringBuilder("ForeignObjectId=")).append(objectId) .append(" and UDFTypeObjectId=") .append(udfId.getPrimaryKeyValue()).toString(); BOIterator<UDFValue> udfVals = session.getEnterpriseLoadManager() .loadUDFValues(fields, where, null); if (udfVals.hasNext()) { UDFValue udfVal = (UDFValue) udfVals.next(); udfVal.setCost(cost); udfVal.update(); } else { UDFValue udfVal = new UDFValue(session); udfVal.setForeignObjectId(objectId); udfVal.setUDFTypeObjectId(udfId); udfVal.setCost(cost); udfVal.create(); } } public static boolean assignProjectCode(Session session, Project project, int codeId) { try { if (codeId > 0) { ProjectCode codeVal = ProjectCode.load(session, new String[] { "CodeTypeObjectId" }, new ObjectId( codeId)); BOIterator<ProjectCodeAssignment> asgItr = project .loadProjectCodeAssignments( new String[] { "ProjectCodeObjectId" }, "ProjectCodeTypeObjectId=" + codeVal.getCodeTypeObjectId(), null); if (asgItr.hasNext()) { ProjectCodeAssignment assignment = asgItr.next(); assignment.setProjectCodeObjectId(new ObjectId(codeId)); assignment.update(); } else { ProjectCodeAssignment assignment = new ProjectCodeAssignment( session); assignment.setProjectCodeObjectId(new ObjectId(codeId)); assignment.setProjectObjectId(project.getObjectId()); assignment.create(); } return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean assignProjectCode(Session session, Project project, String codeValue) { try { if (codeValue != null && codeValue != "") { ObjectId codeTypeObjectId = null; ObjectId codeId = null; EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<ProjectCode> codeItr = elm.loadProjectCodes( new String[] { "Description", "CodeValue", "CodeTypeObjectId" }, "CodeValue='" + codeValue + "'", null); if (codeItr.hasNext()) { ProjectCode code = codeItr.next(); codeTypeObjectId = code.getCodeTypeObjectId(); codeId = code.getObjectId(); } if (codeId == null) { return false; } BOIterator<ProjectCodeAssignment> asgItr = project .loadProjectCodeAssignments( new String[] { "ProjectCodeObjectId" }, "ProjectCodeTypeObjectId=" + codeTypeObjectId, null); if (asgItr.hasNext()) { ProjectCodeAssignment assignment = asgItr.next(); assignment.setProjectCodeObjectId(codeId); assignment.update(); } else { ProjectCodeAssignment assignment = new ProjectCodeAssignment( session); assignment.setProjectCodeObjectId(codeId); assignment.setProjectObjectId(project.getObjectId()); assignment.create(); } return true; } } catch (Exception e) { e.printStackTrace(); } return false; } private static Project createProject(Session session, Opportunity opportunity) throws Exception { Project project = new Project(session); ObjectId epsId = getEPSId(session, NEW_OPP_EPS, true); if (epsId == null) throw new Exception("EPS name " + NEW_OPP_EPS + " can not be created!"); if (opportunity.getLocation().getId() > 0) project.setLocationObjectId(new ObjectId(opportunity.getLocation() .getId())); project.setParentEPSObjectId(epsId); project.setId(opportunity.getId()); project.setName(opportunity.getTitle()); ObjectId projObId = project.create(); opportunity.setProjectId(projObId.toInteger()); return Project.load(session, new String[] { "Id" }, projObId); } public static ObjectId getEPSId(Session session, String epsName, boolean create) throws BusinessObjectException, ServerException, NetworkException { GlobalObjectManager gom = session.getGlobalObjectManager(); BOIterator<EPS> boiEPS = gom.loadEPS(new String[] { "Id" }, "Id='" + epsName + "'", null); ObjectId epsId = null; if (boiEPS.hasNext()) { epsId = boiEPS.next().getObjectId(); } else { if (create == true) { EPS eps = new EPS(session); eps.setId(NEW_OPP_EPS); eps.setName(NEW_OPP_EPS); epsId = eps.create(); } } return epsId; } public static String getUserName(Session session, String userId) throws BusinessObjectException, ServerException, NetworkException { GlobalObjectManager gom = session.getGlobalObjectManager(); BOIterator<User> itr = gom.loadUsers(new String[] { "PersonalName" }, "Name='" + userId + "'", null); if (itr.hasNext()) { return itr.next().getPersonalName(); } return userId; } private static String createNoteBookData(String content, String userName) { String newData = "<div class='contentblock'>"; newData += "<div class='userDetail'>********<strong><span class='userId'>{userName}</span>&nbsp;&nbsp;&nbsp;"; newData += "<span class='timestamp'>{time}</span></strong>****************</div><div class='content'>{data}</div><div>"; SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy HH:mm:ss"); if (content != null && !content.isEmpty()) { newData = newData.replace("{data}", content); newData = newData.replace("{userName}", userName); newData = newData.replace("{time}", sdf.format(new Date())); return newData; } else return ""; } public static int getProjectCodeTypeObjectId(Session session, String codeType) throws BusinessObjectException, ServerException, NetworkException { BOIterator<ProjectCodeType> itr = session.getEnterpriseLoadManager() .loadProjectCodeTypes(new String[] { "Name" }, "Name='" + codeType + "'", null); if (itr.hasNext()) { return itr.next().getObjectId().toInteger(); } return 0; } public static int getProjectCodeObjectId(Project project, String codeType) throws BusinessObjectException, ServerException, NetworkException { BOIterator<ProjectCodeAssignment> itr = project .loadProjectCodeAssignments( new String[] { "ProjectCodeObjectId" }, "ProjectCodeTypeName='" + codeType + "'", null); if (itr.hasNext()) { return itr.next().getProjectCodeObjectId().toInteger(); } return 0; } public static CodeValue getProjectCodeValueAndObjectId(Project project, String codeType) throws BusinessObjectException, ServerException, NetworkException { BOIterator<ProjectCodeAssignment> itr = project .loadProjectCodeAssignments(new String[] { "ProjectCodeObjectId", "ProjectCodeValue", "ProjectCodeDescription" }, "ProjectCodeTypeName='" + codeType + "'", null); if (itr.hasNext()) { ProjectCodeAssignment codeAss = itr.next(); CodeValue option = new CodeValue(codeAss.getProjectCodeObjectId() .toInteger(), codeAss.getProjectCodeDescription()); return option; } return null; } public static List<String> getUserRoles(String userid, Database database) throws SormulaException { List<String> userRoles = new ArrayList<String>(); Table<Roles> roleTbl = database.getTable(Roles.class); List<Roles> roleList = roleTbl.selectAllCustom("where userid = ? ", userid); for (Roles role : roleList) { userRoles.add(role.getRole()); } System.out.println(userRoles.toString()); return userRoles; } public static void getDataFromP6(Session session, Project project, Object object) { getCodeValuesFromP6(project, object); getNoteBookValuesFromP6(session, project, object); getUDFValuesFromP6(session, project, object); } private static void getCodeValuesFromP6(Project project, Object object) { Field[] projectCodes = ReflectionDelegate.getAnnotatedFields( object.getClass(), Code.class); for (Field code : projectCodes) { try { code.setAccessible(true); String codeName = code.getAnnotation(Code.class).name(); code.set(object, PrimaveraDelegate .getProjectCodeValueAndObjectId(project, codeName)); } catch (Exception e) { e.printStackTrace(); } } } private static void getNoteBookValuesFromP6(Session session, Project project, Object object) { Field[] notebookFields = ReflectionDelegate.getAnnotatedFields( object.getClass(), Notebook.class); for (Field notebookField : notebookFields) { try { notebookField.setAccessible(true); String notebook = notebookField.getAnnotation(Notebook.class) .topicName(); notebookField.set(object, PrimaveraDelegate .getProjectNotebookContent(session, project, notebook)); } catch (Exception e) { e.printStackTrace(); } } } private static void getUDFValuesFromP6(Session session, Project project, Object object) { Field[] udfFields = ReflectionDelegate.getAnnotatedFields( object.getClass(), UDF.class); for (Field udfField : udfFields) { try { udfField.setAccessible(true); UDF annotation = udfField.getAnnotation(UDF.class); String title = annotation.name(); switch (annotation.dataType()) { case Constants.UDFDataType.TEXT: udfField.set(object, Utils.getUDFValueText( project.getObjectId(), UDFSubjectArea.PROJECT, title, session)); break; case Constants.UDFDataType.FINISH_DATE: udfField.set(object, Utils.getUDFValueEndDate( project.getObjectId(), UDFSubjectArea.PROJECT, title, session)); break; case Constants.UDFDataType.COST: Cost cost = getUDFValueCost(project.getObjectId(), UDFSubjectArea.PROJECT, title, session); if (cost != null) { if (udfField.getType() == Cost.class) { udfField.set(object, cost); } else if (udfField.getType() == double.class || udfField.getType() == Double.class) { udfField.set(object, cost.doubleValue()); } else if (udfField.getType() == int.class || udfField.getType() == Integer.class) { udfField.set(object, cost.intValue()); } else if (udfField.getType() == float.class || udfField.getType() == Float.class) { udfField.set(object, cost.floatValue()); } else if (udfField.getType() == long.class || udfField.getType() == Long.class) { udfField.set(object, cost.longValue()); } else if (udfField.getType() == String.class) { udfField.set(object, "" + cost.doubleValue()); } } break; case Constants.UDFDataType.INTEGER: udfField.set(object, Utils.getUDFValueEndDate( project.getObjectId(), UDFSubjectArea.PROJECT, title, session)); break; } } catch (Exception e) { e.printStackTrace(); } } } public static void saveDataToP6(Session session, Project project, Object object, String userName) { setCodeValuesToP6(session, project, object); setNoteBookValuesToP6(session, project, object, userName); setUDFValuesToP6(session, project, object); } private static void setCodeValuesToP6(Session session, Project project, Object object) { Field[] projectCodeFields = ReflectionDelegate.getAnnotatedFields( object.getClass(), Code.class); for (Field projectCodeField : projectCodeFields) { try { projectCodeField.setAccessible(true); // System.out.println("Doing : " +projectCodeField); Object value = projectCodeField.get(object); if (value != null) { PrimaveraDelegate.assignProjectCode(session, project, ((CodeValue) value).getId()); } } catch (Exception e) { e.printStackTrace(); } } } private static void setNoteBookValuesToP6(Session session, Project project, Object object, String userName) { Field[] notebookFields = ReflectionDelegate.getAnnotatedFields( object.getClass(), Notebook.class); for (Field notebookField : notebookFields) { try { notebookField.setAccessible(true); Object value = notebookField.get(object); Notebook annotation = notebookField .getAnnotation(Notebook.class); if (value != null) { if (annotation.append()) { PrimaveraDelegate.setProjectNotebookContent(session, project, annotation.topicName(), createNoteBookData(value.toString(), userName), true, true); } else { PrimaveraDelegate.setProjectNotebookContent(session, project, annotation.topicName(), value.toString(), false, true); } } } catch (Exception e) { e.printStackTrace(); } } } private static void setUDFValuesToP6(Session session, Project project, Object object) { Field[] udfFields = ReflectionDelegate.getAnnotatedFields( object.getClass(), UDF.class); for (Field udfField : udfFields) { try { udfField.setAccessible(true); Object value = udfField.get(object); UDF annotation = udfField.getAnnotation(UDF.class); String title = annotation.name(); if (value != null) { switch (annotation.dataType()) { case Constants.UDFDataType.TEXT: Utils.setUDFValueText(session, UDFSubjectArea.PROJECT, title, project.getObjectId(), value.toString()); break; case Constants.UDFDataType.FINISH_DATE: udfField.set(object, Utils.getUDFValueEndDate( project.getObjectId(), UDFSubjectArea.PROJECT, title, session)); Utils.setUDFValueDate(session, UDFSubjectArea.PROJECT, title, project.getObjectId(), new EndDate( (Date) value)); break; case Constants.UDFDataType.COST: Class<?> type = udfField.getType(); Cost cost = null; if (type == int.class || type == Integer.class) { cost = new Cost(udfField.getInt(object)); } else if (type == double.class || type == Double.class) { cost = new Cost(udfField.getDouble(object)); } else if (type == Long.class || type == long.class) { cost = new Cost(udfField.getDouble(object)); } else if (type == String.class) { cost = new Cost(Double.parseDouble(udfField.get( object).toString())); } setUDFValueCost(session, UDFSubjectArea.PROJECT, title, project.getObjectId(), cost); break; case Constants.UDFDataType.INTEGER: Utils.setUDFValueInteger(session, UDFSubjectArea.PROJECT, title, project.getObjectId(), udfField.getInt(object)); break; } } } catch (Exception e) { e.printStackTrace(); } } } private static Cost getUDFValueCost(ObjectId objectId, UDFSubjectArea subjectArea, String title, Session session) throws BusinessObjectException, ServerException, NetworkException { UDFValue value = Utils.getUDFValue(objectId, subjectArea, UDFDataType.COST, title, session); return value != null ? value.getCost() : null; } public static void saveReview(Session session, Review review, String userName) throws BusinessObjectException, ServerException, NetworkException { Project project = Project.load(session, new String[] { "Id" }, new ObjectId(review.getPrjObjId())); saveDataToP6(session, project, review, userName); } public static String getCodeValue(Session session, int codeObjId) throws BusinessObjectException, ServerException, NetworkException { ProjectCode projectCode = ProjectCode.load(session, new String[] { "CodeValue" }, new ObjectId(codeObjId)); return projectCode == null ? null : projectCode.getCodeValue(); } // public static void createProjectCopy(Session session, int projectObjId, // int pmuser) throws Exception { // Project project = Project.load(session, new String[] { "Id", "Name" }, // new ObjectId(projectObjId)); // createProject(session, project, ESTIMATION_EPS, // PropertyLoader.getProperty("project.estimation.nameprefix", // "Estimation For - "), // project.getId().replace("O", "E"), PropertyLoader.getProperty( // "project.estimation.projectcategory", "Estimation"), // ProjectStatus.WHAT_IF); // // chageOppToProposal(session, project, PROPOSAL_EPS, // PropertyLoader.getProperty("project.proposal.nameprefix", // "Proposal For - "), PropertyLoader.getProperty( // "project.proposal.projectcategory", "Proposal")); // // project.setOBSObjectId(new ObjectId(pmuser)); // // } public static Project createProject(Session session, Project project, String epsName, String prefix, String prjId, String projectCategory, ProjectStatus prjStatus) throws Exception { ObjectId epsId = getEPSId(session, epsName, true); if (epsId == null) throw new Exception("EPS name " + PROPOSAL_EPS + " can not be created!"); ObjectId newPrjObjId = project.createCopy(epsId, null, null, null); Project newProject = Project.load(session, new String[] { "Id", "Name" }, newPrjObjId); newProject.setName(prefix + project.getName()); newProject.setId(prjId); if (prjStatus != null) newProject.setStatus(prjStatus); newProject.update(); PrimaveraDelegate.assignProjectCode(session, newProject, projectCategory); return newProject; } public static void setProjectArchived(Session session, int projectObjId) throws Exception { Project project = Project.load(session, new String[] { "ObjectId" }, new ObjectId(projectObjId)); ObjectId epsId = getEPSId(session, ARCHIVED_EPS, true); if (epsId == null) throw new Exception("EPS name " + ARCHIVED_EPS + " can not be created!"); project.setParentEPSObjectId(epsId); project.update(); assignProjectCode(session, project, PropertyLoader.getProperty( "project.archived.projectcategory", "Rejected Opportunity")); } public static List<CodeValue> getOBSUser(Session session) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<UserOBS> userObsItr = elm.loadUserOBS(new String[] { "OBSName", "UserName", "OBSObjectId", "UserObjectId" }, "OBSName='" + PROPOSAL_OBSName + "'", null); List<CodeValue> userList = new ArrayList<CodeValue>(); while (userObsItr.hasNext()) { UserOBS userOb = userObsItr.next(); userList.add(new CodeValue(userOb.getUserObjectId().toInteger(), userOb.getUserName())); } return userList; } public static void chageOppToProposal(Session session, Project project, String epsName, String prefix, String projectCategory) throws Exception { ObjectId epsId = getEPSId(session, epsName, true); if (epsId == null) throw new Exception("EPS name " + PROPOSAL_EPS + " can not be created!"); String prjId = project.getId().replace("O", "P"); project.setId(prjId); project.setName(prefix + project.getName()); project.setParentEPSObjectId(epsId); project.setStatus(ProjectStatus.WHAT_IF); project.update(); PrimaveraDelegate.assignProjectCode(session, project, projectCategory); } public static void getChildOBS(Session session, OBS obs, List<CodeValue> obsList) throws BusinessObjectException, ServerException, NetworkException { BOIterator<OBS> obsItr = obs.loadOBSChildren(new String[] { "ObjectId", "Name" }, null, null); while (obsItr.hasNext()) { OBS ob = obsItr.next(); obsList.add(new CodeValue(ob.getObjectId().toInteger(), ob.getName())); getChildOBS(session, ob, obsList); } } public static List<CodeValue> getOBSList(Session session) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<OBS> obsItr = elm.loadOBS( new String[] { "ObjectId", "Name" }, "Name='" + PROPOSAL_OBSName + "'", null); List<CodeValue> obsList = new ArrayList<CodeValue>(); while (obsItr.hasNext()) { OBS ob = obsItr.next(); getChildOBS(session, ob, obsList); } return obsList; } private static ObjectId getOBSObjectId(Session session, String obsName) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = session.getEnterpriseLoadManager(); BOIterator<OBS> obsItr = elm.loadOBS( new String[] { "ObjectId", "Name" }, "Name='" + obsName + "'", null); while (obsItr.hasNext()) { return obsItr.next().getObjectId(); } return null; } public static void createProjectCopy(Session session, int projectObjId, int pmuser) throws Exception { Project project = Project.load(session, new String[] { "Id", "Name" }, new ObjectId(projectObjId)); Project newPrj = createProject(session, project, ESTIMATION_EPS, PropertyLoader.getProperty("project.estimation.nameprefix", "Estimation For - "), project.getId().replace("O", "E"), PropertyLoader.getProperty( "project.estimation.projectcategory", "Estimation"), ProjectStatus.WHAT_IF); ObjectId obsId = null; try { obsId = getOBSObjectId(session, OBS_ESTIMATIONS); System.out.println("obsid "+obsId); } catch (Exception e) { System.out.println(e.getMessage()); } if (obsId != null){ System.out.println("setobsid on :"+newPrj.getObjectId()); newPrj.setOBSObjectId(obsId); newPrj.update(); } chageOppToProposal(session, project, PROPOSAL_EPS, PropertyLoader.getProperty("project.proposal.nameprefix", "Proposal For - "), PropertyLoader.getProperty( "project.proposal.projectcategory", "Proposal")); project.setOBSObjectId(new ObjectId(pmuser)); project.update(); } public static void setProjectAsActive(Session session, int projectObjId) throws BusinessObjectException, ServerException, NetworkException { Project project = Project.load(session, null, new ObjectId(projectObjId)); project.setStatus(ProjectStatus.ACTIVE); project.update(); } }
Java
package insight.web.controllers; import insight.web.delegates.AjaxJSONDelegate; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.primavera.ServerException; import com.primavera.integration.client.EnterpriseLoadManager; import com.primavera.integration.client.bo.BOIterator; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.ProjectCode; import com.primavera.integration.client.bo.object.ProjectCodeType; import com.primavera.integration.network.NetworkException; @Controller public class ProjectCodeController extends GenericController { @RequestMapping("/loadProjectCode.htm") public ModelAndView loadProjectCode(HttpServletRequest request, HttpServletResponse response) throws Exception { String codeName = request.getParameter("code"); if (codeName != null) { AjaxJSONDelegate.setTextResponse(buildProjectCodeJSON(codeName), response); } return null; } private String buildProjectCodeJSON(String codeName) throws BusinessObjectException, ServerException, NetworkException, JSONException { EnterpriseLoadManager elm = helper.getSession() .getEnterpriseLoadManager(); BOIterator<ProjectCodeType> codeTypeItr = elm.loadProjectCodeTypes( new String[] { "Name" }, "Name='" + codeName + "'", null); List<IProjectCode> list = new ArrayList<IProjectCode>(); if (codeTypeItr.hasNext()) { ProjectCodeType codeType = codeTypeItr.next(); BOIterator<ProjectCode> codeItr = codeType .loadRootProjectCodes(new String[] { "Description", "ObjectId" }); while (codeItr.hasNext()) { ProjectCode code = codeItr.next(); IProjectCode iCode = new IProjectCode(code); list.add(iCode); addChildern(code, iCode); } } Gson gson = new Gson(); return gson.toJson(list); } private void addChildern(ProjectCode parentCode, IProjectCode parentICode) throws BusinessObjectException, ServerException, NetworkException { BOIterator<ProjectCode> codeItr = parentCode.loadProjectCodeChildren( new String[] { "Description", "ObjectId" }, null, null); while (codeItr.hasNext()) { ProjectCode code = codeItr.next(); IProjectCode iCode = new IProjectCode(code); parentICode.addChildern(iCode); addChildern(code, iCode); } } public static class IProjectCode { private int id; private String text; private String closed; private List<IProjectCode> children; public IProjectCode(ProjectCode code) throws BusinessObjectException { setId(code.getObjectId().toInteger()); setText(code.getDescription()); setClosed("true"); } public void addChildern(IProjectCode code) { if (children == null) { children = new ArrayList<IProjectCode>(); } children.add(code); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getClosed() { return closed; } public void setClosed(String closed) { this.closed = closed; } } }
Java
package insight.web.controllers; import insight.miescor.annotations.Constants; import insight.miescor.db.DBManager; import insight.miescor.opp.domain.Assignment; import insight.miescor.opp.domain.AssignmentGrid; import insight.miescor.opp.domain.CodeValue; import insight.miescor.opp.domain.OppReport; import insight.miescor.opp.domain.Opportunity; import insight.miescor.opp.domain.Review; import insight.miescor.opp.domain.Roles; import insight.miescor.opp.domain.WorkflowRole; import insight.web.delegates.AjaxJSONDelegate; import insight.web.delegates.PrimaveraDelegate; import insight.web.delegates.PrimaveraDelegate.ProjectTeam; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.python.modules.jarray; import org.sormula.SormulaException; import org.sormula.Table; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.primavera.ServerException; import com.primavera.common.value.ObjectId; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.network.NetworkException; @Controller public class AddOpportunityController extends GenericController { @Autowired private DBManager dbManager; @RequestMapping("/loadOBSUser.htm") public ModelAndView loadOBSUsers(HttpServletRequest request, HttpServletResponse response) throws Exception { List<CodeValue> obsUser = PrimaveraDelegate.getOBSList(helper .getSession()); Gson gson = new Gson(); String userList = gson.toJson(obsUser); AjaxJSONDelegate.setTextResponse(userList, response); return null; } @RequestMapping("/ResourceDetails.htm") public ModelAndView resouceDetails(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav; String opportunityId = request.getParameter("opportunityId"); String assignmentId = request.getParameter("assId"); String prjObjId = request.getParameter("prjObjId"); int stepId = Assignment .getStepId(dbManager.getDatabase(), assignmentId); if (request.getSession().getAttribute("userName") == null) { mav = new ModelAndView("errorPage"); mav.addObject("ErrorMessage", "Session Expired!"); mav.addObject("Exception", "Session expired please login again!"); return mav; } mav = new ModelAndView("ResourceDetails"); mav.addObject("opportunityId", opportunityId); mav.addObject("prjObjId", prjObjId); mav.addObject("assignmentId", assignmentId); mav.addObject("stepId", stepId); mav.addObject(request.getSession().getAttribute("userName")); return mav; } @RequestMapping("/getResourceDetails.htm") public ModelAndView getResourceDetails(HttpServletRequest request, HttpServletResponse response) throws Exception { String prjObjId = request.getParameter("prjObjId"); Project project = Project.load(helper.getSession(), new String[] { "Id", "Name", "LocationObjectId", "LocationName", "SummaryLevel" }, new ObjectId(Integer.parseInt(prjObjId))); List<ProjectTeam> projectTeam = PrimaveraDelegate.loadProjectTeam( helper.getSession(), project); Gson gson = new Gson(); String projectTeamTxt = gson.toJson(projectTeam); AjaxJSONDelegate.setTextResponse(projectTeamTxt, response); return null; } @RequestMapping("/ViewOpportunity.htm") public ModelAndView viewOpportunity(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav; String opportunityId = request.getParameter("opportunityId"); String assignmentId = request.getParameter("assId"); String prjObjId = request.getParameter("prjObjId"); int stepId = Assignment .getStepId(dbManager.getDatabase(), assignmentId); if (request.getSession().getAttribute("userName") == null) { mav = new ModelAndView("errorPage"); mav.addObject("ErrorMessage", "Session Expired!"); mav.addObject("Exception", "Session expired please login again!"); return mav; } mav = new ModelAndView("ViewOpportunity"); mav.addObject("opportunityId", opportunityId); mav.addObject("prjObjId", prjObjId); mav.addObject("assignmentId", assignmentId); mav.addObject("stepId", stepId); mav.addObject(request.getSession().getAttribute("userName")); return mav; } @RequestMapping("/getCompleteOpportunity.htm") public ModelAndView getCompleteOpportunity(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ServerException, NetworkException { String prjObjId = request.getParameter("prjObjId"); String oppId = request.getParameter("oppId"); Session session = helper.getSession(); Project project = null; try { project = Project.load(session, new String[] { "Id", "Name", "LocationObjectId", "LocationName" }, new ObjectId(Integer.parseInt(prjObjId))); } catch (BusinessObjectException e3) { AjaxJSONDelegate.reportError(response, "Could not load Project [" + prjObjId + "] from Primavera. " + e3.getMessage(), null); e3.printStackTrace(); } // Opportunity oppObj = new Opportunity(helper.getSession(), // project,dbManager.getDatabase()); if (project == null) { AjaxJSONDelegate.reportError(response, "Could not found project [" + prjObjId + "] in Primavera.", null); System.out.println("Could not found project"); return null; } Opportunity oppObj = null; try { oppObj = Opportunity.getOpportunityById(dbManager.getDatabase(), oppId); } catch (SormulaException e2) { AjaxJSONDelegate.reportError(response, "Could not found Opportunity [" + prjObjId + "] in database. " + e2.getMessage(), null); return null; } try { oppObj.loadP6Data(session, project); String notebookContract = PrimaveraDelegate .getProjectNotebookContent(session, project, Constants.ProjectFields.NOTEBOOK_CONTRACT_VALUE); oppObj.setContractValueNotebookText(notebookContract); } catch (BusinessObjectException e2) { e2.printStackTrace(); return null; } Review review = null; try { review = new Review(session, project); } catch (BusinessObjectException e2) { e2.printStackTrace(); } List<Assignment> assList = null; try { assList = Assignment.getAssignmentDetailByOppId( dbManager.getDatabase(), oppObj.getId()); String userPersonalName = ""; for (Assignment assObj : assList) { if (assObj.getUserId() != null && assObj.getUserId().equals("")) { try { userPersonalName = PrimaveraDelegate.getUserName( helper.getSession(), assObj.getUserId()); } catch (Exception e) { e.printStackTrace(); } assObj.setUserId(userPersonalName); } } } catch (Exception e1) { e1.printStackTrace(); } Gson gson = new Gson(); String oppJson = gson.toJson(oppObj); String reviewJson = gson.toJson(review); String assJson = gson.toJson(assList); JSONObject jObj = new JSONObject(); try { jObj.put("opportunity", new JSONObject(oppJson)) .put("review", new JSONObject(reviewJson)) .put("oppStatus", new JSONArray(assJson)) .put("oppCurrentStatus", oppObj.getStatus()); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } System.out.println(oppJson); AjaxJSONDelegate.setResponse(jObj, response); return null; } @RequestMapping("/home.htm") public ModelAndView loadHome(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav; String userId = request.getParameter("userId"); if (userId != "") { mav = new ModelAndView("home"); mav.addObject("userId", userId); mav.addObject("projectType", Constants.ProjectFields.PROJECT_TYPE); mav.addObject("market", Constants.ProjectFields.MARKET); mav.addObject("portfolio", Constants.ProjectFields.PORTFOLIO); String userName = PrimaveraDelegate.getUserName( helper.getSession(), userId); request.getSession().setAttribute("userId", userId); request.getSession().setAttribute("userName", userName); } else { mav = new ModelAndView("errorPage"); mav.addObject("ErrorMessage", "Session Expired!"); mav.addObject("Exception", "Session expired please login again!"); } return mav; } @RequestMapping("/ActionItems.htm") public ModelAndView actionItemsHome(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("ActionItems"); String userId = request.getParameter("userId"); if (userId != "") { String userName = PrimaveraDelegate.getUserName( helper.getSession(), userId); request.getSession().setAttribute("userId", userId); request.getSession().setAttribute("userName", userName); } mav.addObject("userId", userId); Table<Roles> role = dbManager.getDatabase().getTable(Roles.class); Roles roleObj = role.select(userId); if (roleObj != null) mav.addObject("type", roleObj.getRole()); return mav; } @RequestMapping("/listActionItems.htm") public ModelAndView listActionItems(HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = request.getParameter("userId"); List<String> userRoles = PrimaveraDelegate.getUserRoles(userId, dbManager.getDatabase()); String filter = request.getParameter("filter"); List<AssignmentGrid> selOppurtunity = null; if (filter.equalsIgnoreCase("Claimed")) { selOppurtunity = dbManager.getClaimedAssignmentList( new String[] { "Claimed" }, userRoles.toArray(new String[userRoles.size()]), userId); } else { selOppurtunity = dbManager.getAssignmentList(new String[] { "Pending", "Claimed" }, userRoles.toArray(new String[userRoles.size()])); } JSONArray jArray = new JSONArray(); for (AssignmentGrid item : selOppurtunity) { if (item.getStepId() == 4) { if (item.getUserId().equals(userId)) jArray.put(item.getJson()); } else jArray.put(item.getJson()); } AjaxJSONDelegate.setResponse(jArray, response); return null; } @RequestMapping("/AddOpportunity.htm") public ModelAndView addOpportunity(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("AddOpportunity"); String market = request.getParameter("market"); String projectType = request.getParameter("projectType"); String portfolio = request.getParameter("portfolio"); String portfolioName = request.getParameter("portfolioName"); String userId = request.getParameter("userId"); mav.addObject("market", market); mav.addObject("projectType", projectType); mav.addObject("portfolio", portfolio); mav.addObject("portfolioName", portfolioName); mav.addObject("userId", userId); return mav; } @RequestMapping("/saveOpportunity.htm") public ModelAndView saveOpportunity(HttpServletRequest request, HttpServletResponse response) throws JSONException { JSONObject oppJson = null; try { oppJson = readJSON(request); } catch (Exception e) { AjaxJSONDelegate.setResponse(new JSONObject().put("success", false) .put("message", e.getMessage()), response); return null; } System.out.println(oppJson); if (request.getSession().getAttribute("userName") == null) { AjaxJSONDelegate.setResponse(new JSONObject().put("success", false) .put("message", "Session expired, please login again!"), response); return null; } String userName = request.getSession().getAttribute("userName") .toString(); Gson gson = new GsonBuilder().setDateFormat("MM/dd/yyyy").create(); Opportunity oppObj = gson.fromJson(oppJson.toString(), Opportunity.class); if (oppObj.getMarket() != null) oppObj.setDbMarket(oppObj.getMarket().getId()); if (oppObj.getPortfolio() != null) oppObj.setDbPortfolio(oppObj.getPortfolio().getId()); if (oppObj.getProjectType() != null) oppObj.setDbProjectType(oppObj.getProjectType().getId()); try { oppObj.generateId(dbManager.getDatabase(), helper.getSession()); oppObj.save(dbManager.getDatabase(), helper.getSession(), false, userName); AjaxJSONDelegate.setResponse(new JSONObject().put("success", true) .put("message", "Opportunity saved successfully."), response); } catch (Exception e) { AjaxJSONDelegate.setResponse(new JSONObject().put("success", false) .put("message", e.getMessage()), response); } return null; } @RequestMapping("/MapRole.htm") public ModelAndView mapRole(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("MapRole"); // String userId = request.getParameter("userId"); // if (userId != "") { // String userName = PrimaveraDelegate.getUserName( // helper.getSession(), userId); // request.getSession().setAttribute("userId", userId); // request.getSession().setAttribute("userName", userName); // } String userId = request.getParameter("userId"); if (userId != null && userId.equals("admin")) { String userName = PrimaveraDelegate.getUserName( helper.getSession(), userId); request.getSession().setAttribute("userId", userId); request.getSession().setAttribute("userName", userName); mav.addObject("userId", userId); return mav; } return null; } @RequestMapping("/loadUsers.htm") public ModelAndView loadUsers(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONArray jArray = new JSONArray(); if (request.getParameter("showAll") != null && request.getParameter("showAll").equalsIgnoreCase("NO")) { ArrayList<String> list = new ArrayList<String>(); Table<Roles> role = dbManager.getDatabase().getTable(Roles.class); List<Roles> roles = role.selectAll(); for (Roles r : roles) { if (!list.contains(r.getUserid())) { list.add(r.getUserid()); jArray.put(new JSONObject().put("id", r.getUserid()).put( "text", r.getUserid() + " [ " + PrimaveraDelegate.getUserName( helper.getSession(), r.getUserid()) + " ] ")); } } } else { Map<String, String> userList = PrimaveraDelegate.getAllUsers(helper .getSession()); for (Map.Entry<String, String> entry : userList.entrySet()) { jArray.put(new JSONObject().put("id", entry.getKey()).put( "text", entry.getKey() + " [ " + entry.getValue() + " ] ")); } } AjaxJSONDelegate.setResponse(jArray, response); return null; } @RequestMapping("/listRole.htm") public ModelAndView listRole(HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = request.getParameter("userId"); // Table<Roles> role = dbManager.getDatabase().getTable(Roles.class); Table<WorkflowRole> role = dbManager.getDatabase().getTable( WorkflowRole.class); // List<Roles> allroles=role.selectAll(); List<WorkflowRole> allroles = role.selectAll(); Set<String> distinctRole = new HashSet<String>(); for (WorkflowRole r : allroles) { distinctRole.add(r.getRole()); } List<Roles> selRoles = Roles.getRolesByUser(dbManager.getDatabase(), userId); JSONArray jArray = new JSONArray(); for (String d : distinctRole) { for (Roles r : selRoles) { if (d.equalsIgnoreCase(r.getRole()) && userId.equals(r.getUserid())) { jArray.put(new JSONObject() .put("name", r.getRole()) .put("permitted", true) .put("description", getRoleDescription(r.getRole()))); } } } for (String d : distinctRole) { boolean exists = false; for (Roles r : selRoles) { if ((d.equals(r.getRole()))) { exists = true; } } if (exists == false) { jArray.put(new JSONObject().put("name", d) .put("permitted", false) .put("description", getRoleDescription(d))); } } AjaxJSONDelegate.setResponse(jArray, response); return null; } private String getRoleDescription(String roleName) throws SormulaException { return WorkflowRole.getRolesDescription(dbManager.getDatabase(), roleName); } @RequestMapping("/UpdateRole.htm") public ModelAndView updateRole(HttpServletRequest request, HttpServletResponse response) throws JSONException, SormulaException { JSONObject oppJson = null; try { oppJson = readJSON(request); } catch (Exception e) { return null; } try { Table<Roles> role = dbManager.getDatabase().getTable(Roles.class); String targetUser = oppJson.getString("targetUser"); String roles[] = oppJson.getString("roles").split(":"); List<Roles> oldRoles = Roles.getRolesByUser( dbManager.getDatabase(), targetUser); if (oldRoles != null && oldRoles.size() > 0) role.deleteAll(oldRoles); if (!roles[0].equals("")) { for (String r : roles) { Roles newRole = new Roles(); newRole.setId(Roles.generateId(dbManager.getDatabase())); newRole.setRole(r.equalsIgnoreCase("initiator") == true ? "initiator" : r); newRole.setUserid(targetUser); role.insert(newRole); } } AjaxJSONDelegate.setResponse(new JSONObject().put("success", true) .put("message", "Roles Updated successfully."), response); } catch (Exception e) { AjaxJSONDelegate.setResponse( new JSONObject().put("success", false).put("message", "Unable to update Roles. Please try again."), response); } return null; } @RequestMapping("/OppReview.htm") public ModelAndView GetReviewView(HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); String userId = request.getParameter("userId"); String opportunityId = request.getParameter("opportunityId"); String prjObjId = request.getParameter("prjObjId"); String assignmentId = request.getParameter("assignmentId"); ModelAndView mav = null; if (type == null) throw new Exception("Review type missing in the request."); if (type.equalsIgnoreCase("financial")) { mav = new ModelAndView("FinancialReview"); } else if (type.equalsIgnoreCase("capability")) { mav = new ModelAndView("CapabilityReview"); } else if (type.equalsIgnoreCase("legal")) { mav = new ModelAndView("LegalReview"); } else if (type.equalsIgnoreCase("strategic")) { mav = new ModelAndView("StrategicReview"); } else if (type.equalsIgnoreCase("opportunity")) { mav = new ModelAndView("AddOpportunity"); } else if (type.equalsIgnoreCase("prc")) { mav = new ModelAndView("PMAssignment"); } else if (type.equalsIgnoreCase("prc")) { mav = new ModelAndView("PMAssignment"); } else if (type.equalsIgnoreCase("BD")) { mav = new ModelAndView("BD"); } else { mav = new ModelAndView("errorPage"); mav.addObject("ErrorMessage", "Invalid View Type!"); mav.addObject("Exception", "Unexpected review type " + type + "."); } mav.addObject("userId", userId); mav.addObject("opportunityId", opportunityId); mav.addObject("prjObjId", prjObjId); mav.addObject("assignmentId", assignmentId); return mav; } @RequestMapping("/saveReviewData.htm") public ModelAndView saveReviewData(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject oppObj = readJSON(request); System.out.println(oppObj); if (request.getSession().getAttribute("userName") == null) { AjaxJSONDelegate.setResponse(new JSONObject().put("success", false) .put("message", "Session expired, please login again!"), response); return null; } String userName = request.getSession().getAttribute("userName") .toString(); Gson gson = new Gson(); Review review = gson.fromJson(oppObj.toString(), Review.class); PrimaveraDelegate.saveReview(helper.getSession(), review, userName); AjaxJSONDelegate.setResponse( new JSONObject().put("success", true).put("message", "Review saved successfully."), response); return null; } @RequestMapping("/getViewData.htm") public ModelAndView getViewData(HttpServletRequest request, HttpServletResponse response) throws Exception { String prjObjId = request.getParameter("prjObjId"); Gson gson = new Gson(); String jsonData = ""; Project project = Project.load(helper.getSession(), new String[] { "Id", "Name" }, new ObjectId(Integer.parseInt(prjObjId))); Review review = new Review(helper.getSession(), project); jsonData = gson.toJson(review); System.out.println(jsonData); AjaxJSONDelegate.setTextResponse(jsonData, response); return null; } @RequestMapping("/getOpportunityViewData.htm") public ModelAndView getOpportunityViewData(HttpServletRequest request, HttpServletResponse response) throws Exception { String prjObjId = request.getParameter("prjObjId"); Gson gson = new Gson(); String jsonData = ""; Opportunity opprtunity; if (prjObjId != null && !prjObjId.equals("")) { Project project = Project.load(helper.getSession(), new String[] { "Id", "Name", "LocationObjectId", "LocationName" }, new ObjectId(Integer.parseInt(prjObjId))); opprtunity = new Opportunity(helper.getSession(), project); } else { opprtunity = new Opportunity(); } jsonData = gson.toJson(opprtunity); AjaxJSONDelegate.setTextResponse(jsonData, response); return null; } @RequestMapping("/getViewName.htm") public ModelAndView getViewName(HttpServletRequest request, HttpServletResponse response) { // String userId = request.getParameter("userId"); // String id = request.getParameter("assignmentId"); // Assignment // assObj=Assignment.getAssignmentById(dbManager.getDatabase(), id); return null; } @RequestMapping("/oppReport.htm") public ModelAndView getOppReport(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("opportunityReport"); return mav; } @RequestMapping("/pivotChart.htm") public ModelAndView getPivotChart(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("pivotChart"); return mav; } @RequestMapping("/pivotChart1.htm") public ModelAndView getPivotChart1(HttpServletRequest request, HttpServletResponse response) throws JSONException { ModelAndView mav = new ModelAndView("pivotChart1"); return mav; } @RequestMapping("/getPivotData.htm") public ModelAndView getPivotData(HttpServletRequest request, HttpServletResponse response) { try { List<Opportunity> oppList = null; try { oppList = Opportunity.loadAll(dbManager.getDatabase()); } catch (Exception e1) { e1.printStackTrace(); } if (oppList.size() == 0) return null; // List<OppReport> lstReport = new ArrayList(); JSONArray jAry = new JSONArray(); for (Opportunity opp : oppList) { Project project; project = Project.load(helper.getSession(), new String[] { "Id", "Name", "LocationObjectId", "LocationName" }, new ObjectId(opp.getProjectId())); if (project != null) { opp.loadP6Data(helper.getSession(), project); OppReport oppReport = new OppReport(helper.getSession(), project, opp); try { jAry.put(oppReport.toJson()); } catch (JSONException e) { e.printStackTrace(); } } } AjaxJSONDelegate.setResponse(jAry, response); } catch (BusinessObjectException e) { e.printStackTrace(); } catch (ServerException e) { e.printStackTrace(); } catch (NetworkException e) { e.printStackTrace(); } return null; // Opportunity opprtunity = new Opportunity(helper.getSession(), // project); } }
Java
package insight.web.controllers; import insight.miescor.db.DBManager; import insight.miescor.opp.domain.Assignment; import insight.miescor.opp.domain.Opportunity; import insight.miescor.opp.domain.PRCInput; import insight.miescor.opp.domain.Roles; import insight.miescor.opp.domain.Workflow; import insight.miescor.opp.domain.WorkflowRole; import insight.web.delegates.AjaxJSONDelegate; import insight.web.delegates.PrimaveraDelegate; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.sormula.SormulaException; import org.sormula.Table; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class WorkflowController extends GenericController { @Autowired private DBManager dbManager; public static class WorkflowConstants { public static final String CLAIMED = "Claimed"; public static final String COMPLETE = "Complete"; public static final String APPROVE = "Approve"; public static final String PENDING = "Pending"; public static final String BYROLE = "ByRole"; public static final String BYUSER = "ByUser"; public static final String EXPIRED = "Expired"; public static final String REJECT = "Reject"; } @RequestMapping("/OpportunityAction.htm") public ModelAndView claimOpportunity(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject jResult = new JSONObject(); JSONObject jObj; try { jObj = readJSON(request); } catch (IOException e) { e.printStackTrace(); jResult.put("success", false).put("message", "Can not read json String!"); AjaxJSONDelegate.setResponse(jResult, response); return null; } String action = jObj.getString("action"); String pmuser = "None"; if (jObj.has("pmuser")) { pmuser = jObj.getString("pmuser"); } Table<Assignment> assignmentTable = null; Assignment assObj = null; if (action.equalsIgnoreCase("claim")) { assignmentTable = dbManager.getDatabase() .getTable(Assignment.class); assObj = assignmentTable.select(jObj.getInt("id")); assObj.setUserId(jObj.getString("userId")); assObj.setStatus(WorkflowConstants.CLAIMED); assignmentTable.update(assObj); jResult = new JSONObject().put("success", true).put("message", "Opportunity claimed successfully!"); AjaxJSONDelegate.setResponse(jResult, response); return null; } else { assignmentTable = dbManager.getDatabase() .getTable(Assignment.class); assObj = assignmentTable.select(jObj.getInt("id")); assObj.setOpportunity(Opportunity.getOpportunityById( dbManager.getDatabase(), assObj.getOpportunityId())); if (assObj.getStatus().equalsIgnoreCase(WorkflowConstants.CLAIMED) && assObj.getUserId().equalsIgnoreCase( jObj.getString("userId"))) { try { actionOnOpportunity(action, assObj, assignmentTable, pmuser); String suffix=""; if(action.equalsIgnoreCase("approve")) suffix="d"; else suffix="ed"; jResult = new JSONObject().put("success", true).put( "message", "Opportunity " + action + suffix + " successfully!"); } catch (Exception e) { e.printStackTrace(); jResult = new JSONObject() .put("success", false) .put("message", "Error occurred while " + action + "ing Opportunity. Please try manually creating Estimation and Proposal Project in Primavera. " + e.getMessage()); } } else { jResult.put("success", false).put( "message", "Only claimed users can " + action + " the opportunity!"); } AjaxJSONDelegate.setResponse(jResult, response); } return null; } private void actionOnOpportunity(String action, Assignment assObj, Table<Assignment> assignmentTable, String pmuser) throws Exception { int nextStep = assObj.getStepId() + 1; if (action.equals("approve")) { if (assObj.getStepId() == 1) Opportunity.initAssignment(dbManager.getDatabase(), assObj); else { if (!pmuser.equalsIgnoreCase("None")) { PRCInput input = new PRCInput(assObj.getId(), pmuser, dbManager.getDatabase()); input.insertPRC(dbManager.getDatabase()); } assObj.setStatus(WorkflowConstants.COMPLETE); assObj.setEndDate(new Date()); assObj.setOutcome(WorkflowConstants.APPROVE); assignmentTable.update(assObj); boolean isValid = isValidForNextStatus(assObj.getStepId(), assObj.getReviewId(), assObj.getOpportunityId()); if (isValid) { Assignment assObj1 = (Assignment) assObj.clone(); assObj1.setId(Assignment.generateId(dbManager.getDatabase())); assObj1.setStepId(nextStep); assObj1.setEndDate(null); assObj1.setStartDate(new Date()); assObj1.setStatus(WorkflowConstants.PENDING); assObj1.setUserId(""); assObj1.setOutcome(null); Workflow wf = Workflow.getWorkflowByStage( dbManager.getDatabase(), nextStep); if (wf != null) { if (wf.getAssignment() != null) { if (wf.getAssignment().trim() .equalsIgnoreCase(WorkflowConstants.BYROLE)) { assignmentByRole(nextStep, assObj1, assignmentTable); } else if (wf.getAssignment().trim() .equalsIgnoreCase(WorkflowConstants.BYUSER)) { assignmentByUser(nextStep, assObj1, assignmentTable); } } } updateOpportunity(assObj, nextStep); if (assObj.getStepId() == 4) { System.out.println(pmuser); PrimaveraDelegate.createProjectCopy( helper.getSession(), assObj.getProjectObjId(), Integer.parseInt(pmuser)); } if (assObj.getStepId() == 6) { PrimaveraDelegate.setProjectAsActive( helper.getSession(), assObj.getProjectObjId()); } } } } else if (action.equals("reject")) { Workflow wf = Workflow.getWorkflowByStage(dbManager.getDatabase(), assObj.getStepId()); if (wf.getReject() == 0) { throw new Exception("Cannot be rejected at this stage"); } else { int targetStage = wf.getReject(); if (targetStage == 8) { markASArchived(assignmentTable, assObj, targetStage); } else { reAssignmentOnRejection(wf, assObj, assignmentTable); } } } } private void updateOpportunity(Assignment assObj, int targetStage) throws Exception { assObj.getOpportunity().setStatus( Workflow.getStageName(dbManager.getDatabase(), targetStage)); Opportunity.updateOpp(dbManager.getDatabase(), assObj.getOpportunity()); } private void markASArchived(Table<Assignment> assignmentTable, Assignment assObj, int targetStage) throws Exception { List<Assignment> assList = assignmentTable.selectAllCustom( "Where stepId=? and reviewId=? and OpportunityId=?", assObj.getStepId(), assObj.getReviewId(), assObj.getOpportunityId()); for (Assignment assObj1 : assList) { assObj1.setStatus(WorkflowConstants.COMPLETE); assObj1.setOutcome(WorkflowConstants.EXPIRED); assObj1.setEndDate(new Date()); assignmentTable.update(assObj1); } updateOpportunity(assObj, targetStage); PrimaveraDelegate.setProjectArchived(helper.getSession(), assObj.getProjectObjId()); } private void reAssignmentOnRejection(Workflow wf, Assignment assObj, Table<Assignment> assignmentTable) throws Exception { int targetStep = Workflow.getWorkflowByStage(dbManager.getDatabase(), assObj.getStepId()).getReject(); List<WorkflowRole> wfRole = WorkflowRole.getRolesByStep( dbManager.getDatabase(), targetStep); List<Assignment> assList = assignmentTable.selectAllCustom( "Where stepId=? and reviewId=? and OpportunityId=?", targetStep, assObj.getReviewId(), assObj.getOpportunityId()); for (WorkflowRole role : wfRole) { for (Assignment assObj1 : assList) { Assignment newAssObj = new Assignment(role.getRole(), assObj1.getUserId(), assObj1.getApprovalType(), (targetStep == 1) ? assObj1.getReviewId() + 1 : assObj1 .getReviewId(), targetStep, assObj.getOpportunity(), dbManager.getDatabase()); newAssObj.setStatus(WorkflowConstants.CLAIMED); newAssObj.setStartDate(new Date()); newAssObj.insertAssignment(dbManager.getDatabase()); } } assObj.setOutcome(WorkflowConstants.REJECT); assObj.setStatus(WorkflowConstants.COMPLETE); assObj.setEndDate(new Date()); assignmentTable.update(assObj); updateOpportunity(assObj, targetStep); } private void assignmentByRole(int nextStep, Assignment assObj1, Table<Assignment> assignmentTable) throws SormulaException { List<WorkflowRole> roles = WorkflowRole.getRolesByStep( dbManager.getDatabase(), nextStep); if (roles != null) { for (WorkflowRole role : roles) { System.out.println("assignmentByRole "+role.toString()); assObj1.setRole(role.getRole()); assObj1.setId(Assignment.generateId(dbManager.getDatabase())); System.out.println("assignment: "+assObj1.toString()); assignmentTable.insert(assObj1); } } } private void assignmentByUser(int nextStep, Assignment assObj1, Table<Assignment> assignmentTable) throws SormulaException { List<WorkflowRole> roles = WorkflowRole.getRolesByStep( dbManager.getDatabase(), nextStep); for (WorkflowRole role : roles) { List<Roles> users = Roles.getUserByRole(dbManager.getDatabase(), role.getRole()); if (users != null) { for (Roles r : users) { assObj1.setId(Assignment.generateId(dbManager.getDatabase())); assObj1.setUserId(r.getUserid()); assObj1.setRole(role.getRole()); assignmentTable.insert(assObj1); } } } } private boolean isValidForNextStatus(int stepId, int reviewId, String oppId) throws SormulaException { Table<Assignment> assignmentTable = dbManager.getDatabase().getTable( Assignment.class); boolean isValid = true; List<Assignment> assList = assignmentTable.selectAllCustom( "Where stepId=? and reviewId=? and OpportunityId=?", stepId, reviewId, oppId); for (Assignment assObj1 : assList) { if (!assObj1.getStatus().equalsIgnoreCase( WorkflowConstants.COMPLETE) && !assObj1.getStatus().equalsIgnoreCase( WorkflowConstants.REJECT)) isValid = false; } return isValid; } }
Java
package insight.web.controllers; import insight.miescor.db.DBManager; import insight.primavera.common.P6helper; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class GenericController { @Autowired protected P6helper helper; @Autowired protected DBManager dbManager; public static JSONObject readJSON(HttpServletRequest request) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = request.getReader(); String str; while ((str = br.readLine()) != null) { sb.append(str); } try { JSONObject jObj = new JSONObject(sb.toString()); return jObj; } catch (JSONException e) { e.printStackTrace(); return null; } } public P6helper getHelper() { return helper; } public void setHelper(P6helper helper) { this.helper = helper; } public DBManager getDbManager() { return dbManager; } public void setDbManager(DBManager dbManager) { this.dbManager = dbManager; } }
Java
package insight.web.controllers; import insight.common.PropertyLoader; import insight.miescor.annotations.Constants; import insight.miescor.opp.domain.ICurrency; import insight.miescor.opp.domain.ILocation; import insight.web.delegates.AjaxJSONDelegate; import insight.web.delegates.PrimaveraDelegate; import java.io.File; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.primavera.common.value.ObjectId; import com.primavera.integration.client.bo.object.Location; import com.primavera.integration.client.bo.object.ProjectCode; @Controller public class PrimaveraActionsController extends GenericController { @RequestMapping("/loadCurrencies.htm") public ModelAndView loadCurrencies(HttpServletRequest request, HttpServletResponse response) throws Exception { List<ICurrency> currencies = PrimaveraDelegate.loadCurrencyList(helper .getSession()); Gson gson = new Gson(); AjaxJSONDelegate.setTextResponse(gson.toJson(currencies), response); return null; } @RequestMapping("/addNewCustomer.htm") public ModelAndView addNewCustomer(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject jObj = readJSON(request); ProjectCode code = new ProjectCode(helper.getSession()); int prjCodeTypeObjectId = PrimaveraDelegate.getProjectCodeTypeObjectId( helper.getSession(), Constants.ProjectFields.CUSTOMER_NAME); code.setCodeTypeObjectId(new ObjectId(prjCodeTypeObjectId)); code.setCodeValue(jObj.getString("id")); if (!jObj.get("parentId").equals("")) code.setParentObjectId(new ObjectId(jObj.getInt("parentId"))); code.setDescription(jObj.getString("name")); ObjectId objId = code.create(); JSONObject jResult = new JSONObject().put("success", true) .put("id", objId.toInteger()) .put("text", code.getDescription()); AjaxJSONDelegate.setResponse(jResult, response); return null; } @RequestMapping("/addNewLocation.htm") public ModelAndView addNewLocation(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject jObj = readJSON(request); System.out.println(jObj); Location location = new Location(helper.getSession()); location.setName(jObj.getString("name")); if (jObj.has("street1") && jObj.get("street1") != null) location.setAddressLine1(jObj.getString("street1")); if (jObj.has("street2") && jObj.get("street2") != null) location.setAddressLine1(jObj.getString("street2")); if (jObj.has("city") && jObj.get("city") != null) location.setCity(jObj.getString("city")); if (jObj.has("state") && jObj.get("state") != null) location.setState(jObj.getString("state")); if (jObj.has("postalCode") && jObj.get("postalCode") != null) location.setPostalCode(jObj.getString("postalCode")); if (jObj.has("country") && jObj.get("country") != null) location.setCountryCode(jObj.getString("country")); location.setLatitude(0); location.setLongitude(0); ObjectId locId = location.create(); JSONObject jResult = new JSONObject().put("success", true) .put("id", locId).put("text", jObj.getString("name")); AjaxJSONDelegate.setResponse(jResult, response); return null; } @RequestMapping("/loadLocations.htm") public ModelAndView loadLocations(HttpServletRequest request, HttpServletResponse response) throws Exception { List<ILocation> location = PrimaveraDelegate.loadLocationList(helper .getSession()); Gson gson = new Gson(); AjaxJSONDelegate.setTextResponse(gson.toJson(location), response); return null; } @RequestMapping("/getCountryList.htm") public ModelAndView getCountryList(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println(PropertyLoader.getProperty( "primavera.country.list", "")); File file = new File(PropertyLoader.getProperty( "primavera.country.list", "")); JSONArray jAry=new JSONArray(); if (file.exists()) { String []ary; for (String line : FileUtils.readLines(file)){ ary=line.split("::"); jAry.put(new JSONObject().put("text", ary[0]).put("value",ary[1])); } }else{ System.out.println("Country list file not found"); } AjaxJSONDelegate.setResponse(jAry, response); return null; } }
Java
package insight.miescor.opp.domain; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import org.sormula.annotation.Where; import org.sormula.annotation.Wheres; import org.sormula.annotation.WhereField; @Wheres({ @Where(name="role", whereFields=@WhereField(name="role", comparisonOperator="IN")) }) public class Roles { private String userid; private int id; private String role; public Roles() { } public static int generateId(Database database) throws SormulaException { NumberGenerator numGen = NumberGenerator.loadNextNum(database, "RoleId"); return numGen.getSeriesCurrentNum(); } public Roles(JSONObject roleObj) throws JSONException { id = roleObj.has("id") ? Integer.parseInt(roleObj.getString("id")) : 0; userid = roleObj.has("userid") ? roleObj.getString("userid") : ""; role = roleObj.has("role") ? roleObj.getString("role") : ""; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public static List<Roles> getUserByRole(Database database,String role) throws SormulaException{ Table<Roles> roleTbl =database.getTable(Roles.class); List<Roles> roleList=roleTbl.selectAllCustom("where role = ? ", role); return roleList; } public static List<Roles> getRolesByUser(Database database,String userid) throws SormulaException{ Table<Roles> roleTbl =database.getTable(Roles.class); List<Roles> roleList=roleTbl.selectAllCustom("where userid = ? ", userid); return roleList; } @Override public String toString() { return "Roles [userid=" + userid + ", id=" + id + ", role=" + role + "]"; } }
Java
package insight.miescor.opp.domain; import java.util.Date; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; public class PRCInput implements Cloneable { private int id; private int assignmentid; private String objectid; private Date createdon; public static int generateId(Database database) throws SormulaException { NumberGenerator numGen = NumberGenerator.loadNextNum(database, "PrcId"); return numGen.getSeriesCurrentNum(); } public PRCInput() { } public PRCInput(int assignmentid,String objectid,Database database) throws SormulaException { this.id = generateId(database); this.assignmentid=assignmentid; this.objectid=objectid; this.createdon=new Date(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAssignmentid() { return assignmentid; } public void setAssignmentid(int assignmentid) { this.assignmentid = assignmentid; } public String getObjectid() { return objectid; } public void setObjectid(String objectid) { this.objectid = objectid; } public Date getCreatedon() { return createdon; } public void setCreatedon(Date createdon) { this.createdon = createdon; } public void insertPRC(Database database) throws SormulaException { Table<PRCInput> prcTable = database.getTable(PRCInput.class); prcTable.insert(this); } }
Java
package insight.miescor.opp.domain; public class CodeValue { private int id; private String value; public CodeValue() { } public CodeValue(int id, String value) { this.id=id; this.value=value; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
Java
package insight.miescor.opp.domain; import insight.miescor.annotations.Code; import insight.miescor.annotations.Constants; import insight.miescor.annotations.Notebook; import insight.miescor.annotations.UDF; import insight.web.delegates.PrimaveraDelegate; import com.primavera.ServerException; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.network.NetworkException; public class Review { // region Common fields private String opportunityId; private int prjObjId; private String userId; private int assignmentId; @Notebook(topicName = Constants.ProjectFields.ADD_NOTES, append = true) private String addNotes; @Code(name = Constants.ProjectFields.RISK_RATING) private CodeValue riskRating; // endregion // region Capability Review fields @Notebook(topicName = Constants.ProjectFields.CAPABILITY_ASS) private String capabilityAssesment; @Code(name = Constants.ProjectFields.BANDWIDTH) private CodeValue bandwidth; @Code(name = Constants.ProjectFields.CAPABILITY) private CodeValue capability; // endregion // region Financial Review fields @UDF(name = Constants.ProjectFields.CONTRACT_VALUE_EX_TAXES, dataType = Constants.UDFDataType.COST) private double contractValue; @Notebook(topicName = Constants.ProjectFields.REALIZATION) private String realization; @Notebook(topicName = Constants.ProjectFields.FIN_RISK_ASSESMENT) private String finRiskAssessment; @Notebook(topicName = Constants.ProjectFields.FIN_VIABILITY) private String finViability; @Notebook(topicName = Constants.ProjectFields.FUNDING_DETAILS) private String fundingDetail; @Code(name = Constants.ProjectFields.CONTRACT_VALUE_RATING) private CodeValue contractValueRating; @Code(name = Constants.ProjectFields.FIN_VIABILITY_RATING) private CodeValue finViabilityRating; @Code(name = Constants.ProjectFields.REALIZATION_RATING) private CodeValue realizationRating; @Code(name = Constants.ProjectFields.PROJECT_FUNDING) private CodeValue projectFunding; // endregion Financial Review fields // region Legal Review fields @Notebook(topicName = Constants.ProjectFields.FAV_TERMS) private String favourableTerms; @Notebook(topicName = Constants.ProjectFields.ADV_TERMS) private String adverseTerms; @Notebook(topicName = Constants.ProjectFields.REG_RATING) private String regulatoryRequirement; @Code(name = Constants.ProjectFields.REG_RATING) private CodeValue regulatoryRating; // endregion Legal Review fields // region Strategic Review fields @Notebook(topicName = Constants.ProjectFields.STRATEGIC_IMP) private String strategicImportance; @Notebook(topicName = Constants.ProjectFields.CUSTOMER) private String customerConsultant; @Notebook(topicName = Constants.ProjectFields.ALIGNMENT) private String alignment; @Code(name = Constants.ProjectFields.LOCATION_RATING) private CodeValue locationRating; @Code(name = Constants.ProjectFields.BUILD_TRACK) private CodeValue buildTrack; @Code(name = Constants.ProjectFields.MARKET_PENETRATION) private CodeValue marketPenetration; @Code(name = Constants.ProjectFields.IS_COMPULSIVE_WIN) private CodeValue isCompulsiveWin; @Code(name = Constants.ProjectFields.WIN_RATIO) private CodeValue winRatio; @Code(name = Constants.ProjectFields.TYPE_OF_WORK) private CodeValue workType; @Code(name = Constants.ProjectFields.CUSTOMER_RATING) private CodeValue customerRating; @Code(name = Constants.ProjectFields.CONSULTANT_RATING) private CodeValue consultantRating; @Code(name = Constants.ProjectFields.WINNABILITY) private CodeValue Winnability; // endregion Strategic Review fields public Review(Session session, Project project) throws BusinessObjectException, ServerException, NetworkException { if (project != null) { this.setPrjObjId(project.getObjectId().toInteger()); this.setOpportunityId(project.getId()); PrimaveraDelegate.getDataFromP6(session, project, this); } } // region common fields getter/setter public String getOpportunityId() { return opportunityId; } public void setOpportunityId(String opportunityId) { this.opportunityId = opportunityId; } public int getPrjObjId() { return prjObjId; } public void setPrjObjId(int prjObjId) { this.prjObjId = prjObjId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getAssignmentId() { return assignmentId; } public void setAssignmentId(int assignmentId) { this.assignmentId = assignmentId; } public String getAddNotes() { return addNotes; } public void setAddNotes(String addNotes) { this.addNotes = addNotes; } public CodeValue getRiskRating() { return riskRating; } public void setRiskRating(CodeValue riskRating) { this.riskRating = riskRating; } // endregion common fields properties // region Capability Review getter/setter public String getCapabilityAssesment() { return capabilityAssesment; } public void setCapabilityAssesment(String capabilityAssesment) { this.capabilityAssesment = capabilityAssesment; } public CodeValue getBandwidth() { return bandwidth; } public void setBandwidth(CodeValue bandwidth) { this.bandwidth = bandwidth; } public CodeValue getCapability() { return capability; } public void setCapability(CodeValue capability) { this.capability = capability; } // endregion Capability Review properties // region Financial Review getter/setter public double getContractValue() { return contractValue; } public void setContractValue(double contractValue) { this.contractValue = contractValue; } public String getRealization() { return realization; } public void setRealization(String realization) { this.realization = realization; } public String getFinRiskAssessment() { return finRiskAssessment; } public void setFinRiskAssessment(String finRiskAssessment) { this.finRiskAssessment = finRiskAssessment; } public String getFinViability() { return finViability; } public void setFinViability(String finViability) { this.finViability = finViability; } public String getFundingDetail() { return fundingDetail; } public void setFundingDetail(String fundingDetail) { this.fundingDetail = fundingDetail; } public CodeValue getContractValueRating() { return contractValueRating; } public void setContractValueRating(CodeValue contractValueRating) { this.contractValueRating = contractValueRating; } public CodeValue getFinViabilityRating() { return finViabilityRating; } public void setFinViabilityRating(CodeValue finViabilityRating) { this.finViabilityRating = finViabilityRating; } public CodeValue getRealizationRating() { return realizationRating; } public void setRealizationRating(CodeValue realizationRating) { this.realizationRating = realizationRating; } public CodeValue getProjectFunding() { return projectFunding; } public void setProjectFunding(CodeValue projectFunding) { this.projectFunding = projectFunding; } // endregion Financial Review Properties // region Legal Review getter/setter public String getFavourableTerms() { return favourableTerms; } public void setFavourableTerms(String favourableTerms) { this.favourableTerms = favourableTerms; } public String getAdverseTerms() { return adverseTerms; } public void setAdverseTerms(String adverseTerms) { this.adverseTerms = adverseTerms; } public String getRegulatoryRequirement() { return regulatoryRequirement; } public void setRegulatoryRequirement(String regulatoryRequirement) { this.regulatoryRequirement = regulatoryRequirement; } public CodeValue getRegulatoryRating() { return regulatoryRating; } public void setRegulatoryRating(CodeValue regulatoryRating) { this.regulatoryRating = regulatoryRating; } // endregion Legal Review Properties // region Strategic Review getter/setter public String getStrategicImportance() { return strategicImportance; } public void setStrategicImportance(String strategicImportance) { this.strategicImportance = strategicImportance; } public String getCustomerConsultant() { return customerConsultant; } public void setCustomerConsultant(String customerConsultant) { this.customerConsultant = customerConsultant; } public String getAlignment() { return alignment; } public void setAlignment(String alignment) { this.alignment = alignment; } public CodeValue getLocationRating() { return locationRating; } public void setLocationRating(CodeValue locationRating) { this.locationRating = locationRating; } public CodeValue getBuildTrack() { return buildTrack; } public void setBuildTrack(CodeValue buildTrack) { this.buildTrack = buildTrack; } public CodeValue getMarketPenetration() { return marketPenetration; } public void setMarketPenetration(CodeValue marketPenetration) { this.marketPenetration = marketPenetration; } public CodeValue getIsCompulsiveWin() { return isCompulsiveWin; } public void setIsCompulsiveWin(CodeValue isCompulsiveWin) { this.isCompulsiveWin = isCompulsiveWin; } public CodeValue getWinRatio() { return winRatio; } public void setWinRatio(CodeValue winRatio) { this.winRatio = winRatio; } public CodeValue getWorkType() { return workType; } public void setWorkType(CodeValue workType) { this.workType = workType; } public CodeValue getCustomerRating() { return customerRating; } public void setCustomerRating(CodeValue customerRating) { this.customerRating = customerRating; } public CodeValue getConsultantRating() { return consultantRating; } public void setConsultantRating(CodeValue consultantRating) { this.consultantRating = consultantRating; } public CodeValue getWinnability() { return Winnability; } public void setWinnability(CodeValue winnability) { Winnability = winnability; } // endregion Strategic Review Properties }
Java
package insight.miescor.opp.domain; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; public class Customer { private String id; private String name; private String sapId; public Customer() { } public Customer(JSONObject cusObj) throws JSONException { id = cusObj.has("id") ? cusObj.getString("id") : ""; name = cusObj.has("name") ? cusObj.getString("name") : ""; sapId = cusObj.has("sapId") ? cusObj.getString("sapId") : ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSapId() { return sapId; } public void setSapId(String sapId) { this.sapId = sapId; } public static List<Customer> loadAll(Database database) throws Exception { Table<Customer> customerTable = database.getTable(Customer.class); return customerTable.selectAll(); } public void save(Database database) throws SormulaException { Table<Customer> customerTable = database.getTable(Customer.class); customerTable.insert(this); } }
Java
package insight.miescor.opp.domain; public class WorkflowMaster { private int id; private String workflowName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getWorkflowName() { return workflowName; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } }
Java
package insight.miescor.opp.domain; import insight.miescor.annotations.Code; import insight.miescor.annotations.Constants; import insight.miescor.annotations.Notebook; import insight.miescor.annotations.UDF; import insight.web.delegates.PrimaveraDelegate; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.converters.DateConverter; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import org.sormula.annotation.Column; import org.sormula.annotation.Transient; import com.primavera.ServerException; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.network.NetworkException; public class Opportunity { // region fields private String id; @Column(name = "market") private int dbMarket; @Column(name = "portfolio") private int dbPortfolio; @Column(name = "projectType") private int dbProjectType; @Code(name = Constants.ProjectFields.MARKET) @Transient private CodeValue market; @Transient @Code(name = Constants.ProjectFields.PORTFOLIO) private CodeValue portfolio; @Transient @Code(name = Constants.ProjectFields.PROJECT_TYPE) private CodeValue projectType; private String title; @UDF(name = Constants.ProjectFields.INITIATOR, dataType = Constants.UDFDataType.TEXT) @Column(name = "initiator") private String userId; private String status; private int projectId; @Transient private List<ContractVal> contractVal; @Transient private String contractValueNotebookText; @Transient @UDF(name = Constants.ProjectFields.PACKAGE_NAME, dataType = Constants.UDFDataType.TEXT) private String packageName; @Transient @UDF(name = Constants.ProjectFields.CONTRACT_NUMBER, dataType = Constants.UDFDataType.TEXT) private String contractNo; @Transient @Notebook(topicName = Constants.ProjectFields.PRJ_DESCRIPTION) private String description; @Transient private CodeValue location; @Code(name = Constants.ProjectFields.CUSTOMER_NAME) @Transient private CodeValue customer; @Code(name = Constants.ProjectFields.IS_JV) @Transient private CodeValue isJV; @Transient @Notebook(topicName = Constants.ProjectFields.JV_DETAILS) private String jvDetails; @Transient @Notebook(topicName = Constants.ProjectFields.REG_REQUIREMENT) private String regulatoryRequirement; @Transient @Notebook(topicName = Constants.ProjectFields.RISK_SYNOPSIS) private String riskSynopsis; @Transient @Notebook(topicName = Constants.ProjectFields.FUNDING_DETAILS) private String fundingDetail; @Transient @Notebook(topicName = Constants.ProjectFields.COMPETITVE_ANALYSIS) private String competitiveAnaiysis; @Transient @UDF(name = Constants.ProjectFields.BID_DATE, dataType = Constants.UDFDataType.FINISH_DATE) private Date bidDate; @Transient @UDF(name = Constants.ProjectFields.AWARD_DATE, dataType = Constants.UDFDataType.FINISH_DATE) private Date awardDate; @Transient @UDF(name = Constants.ProjectFields.PRJ_START_DATE, dataType = Constants.UDFDataType.FINISH_DATE) private Date prjStDate; @Transient @UDF(name = Constants.ProjectFields.PROJECT_DURTION, dataType = Constants.UDFDataType.TEXT) private String prjDuration; @Transient @Notebook(topicName = Constants.ProjectFields.ADD_NOTES_ON_TIMELINE) private String timelineNotes; // endregion fields public Opportunity() { } public Opportunity(Opportunity opp) { try { ConvertUtils.register(new DateConverter(null), Date.class); BeanUtils.copyProperties(this, opp); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Opportunity(Session session, Project project) throws BusinessObjectException, ServerException, NetworkException { this.title = project.getName(); this.projectId = project.getObjectId().toInteger(); this.location = new CodeValue( project.getLocationObjectId().toInteger(), project.getLocationName()); this.id=project.getId(); PrimaveraDelegate.getDataFromP6(session, project, this); String contractValue = PrimaveraDelegate.getProjectNotebookContent( session, project, Constants.ProjectFields.NOTEBOOK_CONTRACT_VALUE); if (contractValue != null && !contractValue.equals("")) { List<ContractVal> lstContractValue = new ArrayList<ContractVal>(); for (String costData : contractValue.split("</br>")) { String costValue[] = costData.split(" "); lstContractValue .add(new ContractVal(costValue[0], costValue[1])); } } } public void loadP6Data(Session session, Project project) throws BusinessObjectException { this.title = project.getName(); this.projectId = project.getObjectId().toInteger(); this.location = new CodeValue( project.getLocationObjectId().toInteger(), project.getLocationName()); this.id=project.getId(); PrimaveraDelegate.getDataFromP6(session, project, this); String contractValue = PrimaveraDelegate.getProjectNotebookContent( session, project, Constants.ProjectFields.NOTEBOOK_CONTRACT_VALUE); if (contractValue != null && !contractValue.equals("")) { List<ContractVal> lstContractValue = new ArrayList<ContractVal>(); for (String costData : contractValue.split("</br>")) { String costValue[] = costData.split(" "); lstContractValue .add(new ContractVal(costValue[0], costValue[1])); } } } public String generateId(Database database, Session session) throws SormulaException, BusinessObjectException, ServerException, NetworkException { SimpleDateFormat sdf = new SimpleDateFormat("yy"); String prefix = PrimaveraDelegate.getCodeValue(session, portfolio.getId()) + "O" + sdf.format(new Date()); System.out.println("Prefix : " + prefix); NumberGenerator numGen = NumberGenerator.loadNextNum(database, prefix); String runNum = "0000" + numGen.getSeriesCurrentNum(); System.out.println("running number : " + runNum); setId(prefix + "-" + runNum.substring(runNum.length() - 4)); System.out.println("ID " + getId()); return getId(); } public static List<Opportunity> loadAll(Database database) throws Exception { Table<Opportunity> oppTable = database.getTable(Opportunity.class); return oppTable.selectAll(); } public void save(Database database, Session session, boolean doSubmit, String userName) throws Exception { try { PrimaveraDelegate.saveOpportunity(session, this, userName); } catch (Exception e) { e.printStackTrace(); } if (this.getProjectId() == 0) { throw new Exception( "Project ID: Unique constraint (Project ID) violated. The value " + this.getId() + " of the field Project ID already exists."); } Table<Opportunity> oppTable = database.getTable(Opportunity.class); this.setStatus("Pending"); oppTable.insert(this); Assignment assObj = new Assignment("initiator", this.getUserId(), "Single", 1, 1, this, database); assObj.setStatus("Claimed"); assObj.setStartDate(new Date()); assObj.insertAssignment(database); if (doSubmit) { initAssignment(database, assObj); } } public static void initAssignment(Database database, Assignment assObj) throws SormulaException, CloneNotSupportedException { Table<Assignment> assignmentTable = database.getTable(Assignment.class); assObj.setStatus("Complete"); assObj.setEndDate(new Date()); assObj.setOutcome("Initiate"); assignmentTable.update(assObj); initiateOpportunity(assObj, assignmentTable, database); } public static void initiateOpportunity(Assignment assObj, Table<Assignment> assignmentTable, Database database) throws SormulaException, CloneNotSupportedException { int nextStep = assObj.getStepId()+1; Assignment assObj1 = (Assignment) assObj.clone(); //assObj1.setId(Assignment.generateId(database)); assObj1.setStepId(nextStep); assObj1.setEndDate(null); assObj1.setStartDate(new Date()); assObj1.setStatus("Pending"); assObj1.setUserId(""); assObj1.setOutcome(null); List<WorkflowRole> roles=WorkflowRole.getRolesByStep(database, nextStep); if(roles != null){ for(WorkflowRole role : roles){ assObj1.setRole(role.getRole()); assObj1.setId(Assignment.generateId(database)); System.out.println(role.getRole() + " " + assObj.getId()); assignmentTable.insert(assObj1); } } assObj.getOpportunity().setStatus(Workflow.getStageName(database, nextStep)); Table<Opportunity> oppTable = database.getTable(Opportunity.class); oppTable.update(assObj.getOpportunity()); } public void update(Database database) throws SormulaException { Table<Opportunity> oppTable = database.getTable(Opportunity.class); oppTable.update(this); } public static void updateOpp(Database database, Opportunity opp) throws SormulaException { Table<Opportunity> oppTable = database.getTable(Opportunity.class); oppTable.update(opp); } public static Opportunity getOpportunityById(Database database, String itemId) throws SormulaException { Table<Opportunity> oppTable = database.getTable(Opportunity.class); return oppTable.select(itemId); } // region Getters & Setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getContractNo() { return contractNo; } public void setContractNo(String contractNo) { this.contractNo = contractNo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CodeValue getLocation() { return location; } public void setLocation(CodeValue location) { this.location = location; } public CodeValue getCustomer() { return customer; } public void setCustomer(CodeValue customer) { this.customer = customer; } public CodeValue getIsJV() { return isJV; } public void setIsJV(CodeValue isJV) { this.isJV = isJV; } public String getJvDetails() { return jvDetails; } public void setJvDetails(String jvDetails) { this.jvDetails = jvDetails; } public String getRegulatoryRequirement() { return regulatoryRequirement; } public void setRegulatoryRequirement(String regulatoryRequirement) { this.regulatoryRequirement = regulatoryRequirement; } public String getRiskSynopsis() { return riskSynopsis; } public void setRiskSynopsis(String riskSynopsis) { this.riskSynopsis = riskSynopsis; } public String getFundingDetail() { return fundingDetail; } public void setFundingDetail(String fundingDetail) { this.fundingDetail = fundingDetail; } public String getCompetitiveAnaiysis() { return competitiveAnaiysis; } public void setCompetitiveAnaiysis(String competitiveAnaiysis) { this.competitiveAnaiysis = competitiveAnaiysis; } public Date getBidDate() { return bidDate; } public void setBidDate(Date bidDate) { this.bidDate = bidDate; } public Date getAwardDate() { return awardDate; } public void setAwardDate(Date awardDate) { this.awardDate = awardDate; } public Date getPrjStDate() { return prjStDate; } public void setPrjStDate(Date prjStDate) { this.prjStDate = prjStDate; } public String getPrjDuration() { return prjDuration; } public void setPrjDuration(String prjDuration) { this.prjDuration = prjDuration; } public String getTimelineNotes() { return timelineNotes; } public void setTimelineNotes(String timelineNotes) { this.timelineNotes = timelineNotes; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public List<ContractVal> getContractVal() { return contractVal; } public void setContractVal(List<ContractVal> contractVal) { this.contractVal = contractVal; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public void setId(String id) { this.id = id; } public String getId() { return id; } public CodeValue getMarket() { return market; } public void setMarket(CodeValue market) { this.market = market; if (market != null) this.dbMarket = market.getId(); } public CodeValue getProjectType() { return projectType; } public void setProjectType(CodeValue projectType) { this.projectType = projectType; if (projectType != null) this.dbProjectType = projectType.getId(); } public static class ContractVal { private String value; private String currency; public ContractVal(String value, String currency) { this.value = value; this.currency = currency; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } } public CodeValue getPortfolio() { return portfolio; } public void setPortfolio(CodeValue portfolio) { this.portfolio = portfolio; if (portfolio != null) this.dbPortfolio = portfolio.getId(); } public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } // endregion Getters & Setters public int getDbMarket() { return dbMarket; } public void setDbMarket(int dbMarket) { this.dbMarket = dbMarket; } public int getDbPortfolio() { return dbPortfolio; } public void setDbPortfolio(int dbPortfolio) { this.dbPortfolio = dbPortfolio; } public int getDbProjectType() { return dbProjectType; } public void setDbProjectType(int dbProjectType) { this.dbProjectType = dbProjectType; } public String getContractValueNotebookText() { return contractValueNotebookText; } public void setContractValueNotebookText(String contractValueNotebookText) { this.contractValueNotebookText = contractValueNotebookText; } }
Java
package insight.miescor.opp.domain; import insight.miescor.annotations.Code; import insight.miescor.annotations.Constants; import insight.miescor.annotations.UDF; import insight.web.delegates.PrimaveraDelegate; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.axis.utils.BeanUtils; import org.json.JSONException; import org.json.JSONObject; import com.primavera.ServerException; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.network.NetworkException; public class OppReport extends Opportunity { @UDF(name = Constants.ProjectFields.UDF_CONTRACT_VALUE, dataType = Constants.UDFDataType.COST) private double contractValue; @Code(name = Constants.ProjectFields.RISK_RATING) private CodeValue riskRating; @Code(name = Constants.ProjectFields.IS_COMPULSIVE_WIN) private CodeValue isCompulsiveWin; private Date oppInitiatedDate; // @Code(name = Constants.ProjectFields.pr) private String oppStatus; public OppReport(Session session, Project project) throws BusinessObjectException, ServerException, NetworkException { super(session, project); PrimaveraDelegate.getDataFromP6(session, project, this); } public OppReport(Session session, Project project, Opportunity opp) { super(opp); PrimaveraDelegate.getDataFromP6(session, project, this); } public double getContractValue() { return contractValue; } public void setContractValue(double contractValue) { this.contractValue = contractValue; } public CodeValue getRiskRating() { return riskRating; } public void setRiskRating(CodeValue riskRating) { this.riskRating = riskRating; } public CodeValue getIsCompulsiveWin() { return isCompulsiveWin; } public void setIsCompulsiveWin(CodeValue isCompulsiveWin) { this.isCompulsiveWin = isCompulsiveWin; } public Date getOppInitiatedDate() { return oppInitiatedDate; } public void setOppInitiatedDate(Date oppInitiatedDate) { this.oppInitiatedDate = oppInitiatedDate; } public String getOppStatus() { return oppStatus; } public void setOppStatus(String oppStatus) { this.oppStatus = oppStatus; } public JSONObject toJson() throws JSONException { JSONObject jObj = new JSONObject(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); jObj.put("Title", this.getTitle()) .put("Package Name", this.getPackageName()) .put("Contract No.", this.getContractNo()) .put("Location", (this.getLocation() != null ? this.getLocation() .getValue() : "")) .put("Contract Value", this.getContractValue()) .put("Customer", (this.getCustomer() != null ? this.getCustomer() .getValue() : "")) .put("Portfolio", (this.getPortfolio() != null ? this.getPortfolio() .getValue() : "")) .put("Project Type", (this.getProjectType() != null ? this.getProjectType() .getValue() : "")) .put("Risk", (this.getRiskRating() != null ? this.getRiskRating() .getValue() : "0")) .put("Compulsive Win", (this.getIsCompulsiveWin() != null ? this .getIsCompulsiveWin().getValue() : "")) .put("InitiatedBy", (this.getUserId() != null ? this.getUserId() : "")) // .put("InitiatedOn", this.getOppInitiatedDate()) .put("Bid Date", (this.getBidDate() != null ? sdf.format(this .getBidDate()) : null)) .put("Award Date", (this.getAwardDate() != null ? sdf.format(this .getAwardDate()) : null)); return jObj; } }
Java
package insight.miescor.opp.domain; import java.util.Date; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; public class Activity { private int id; private Date completedon; private String completedby; private String status; private String itemid; public Activity() { } public Activity(Date completedon, String completedby, String status, String itemid) { this.completedon=completedon; this.completedby=completedby; this.status=status; this.itemid=itemid; } public void save(Database database) throws SormulaException { Table<Activity> activityTable = database.getTable(Activity.class); activityTable.insert(this); } public Date getCompletedon() { return completedon; } public void setCompletedon(Date completedon) { this.completedon = completedon; } public String getCompletedby() { return completedby; } public void setCompletedby(String completedby) { this.completedby = completedby; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getItemid() { return itemid; } public void setItemid(String itemid) { this.itemid = itemid; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "Activity [id=" + id + ", completedon=" + completedon + ", completedby=" + completedby + ", status=" + status + ", itemid=" + itemid + "]"; } }
Java
package insight.miescor.opp.domain; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; public class NumberGenerator { private String seriesKey; private Integer seriesCurrentNum; public NumberGenerator() { } public NumberGenerator(String key) { seriesKey = key; seriesCurrentNum = 1; } public static NumberGenerator loadNextNum(Database database, String key) throws SormulaException { Table<NumberGenerator> numGenTable = database .getTable(NumberGenerator.class); NumberGenerator numGenerator = numGenTable.select(key); if (numGenerator != null) { numGenerator.setSeriesCurrentNum(numGenerator.seriesCurrentNum + 1); numGenTable.update(numGenerator); } else { numGenerator = new NumberGenerator(key); numGenTable.save(numGenerator); } return numGenerator; } public Integer getSeriesCurrentNum() { return seriesCurrentNum; } public void setSeriesCurrentNum(Integer seriesCurrentNum) { this.seriesCurrentNum = seriesCurrentNum; } public String getSeriesKey() { return seriesKey; } public void setSeriesKey(String seriesKey) { this.seriesKey = seriesKey; } }
Java
package insight.miescor.opp.domain; import java.util.List; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import org.sormula.annotation.Where; import org.sormula.annotation.WhereField; import org.sormula.annotation.Wheres; @Wheres({ @Where(name="step", whereFields=@WhereField(name="step", comparisonOperator="=")) }) public class WorkflowRole { private int id; private int step; private String role; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getStep() { return step; } public void setStep(int step) { this.step = step; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public static List<WorkflowRole> getRolesByStep(Database database, int step)throws SormulaException{ Table<WorkflowRole> roleTable = database.getTable(WorkflowRole.class); System.out.println("Role: "+roleTable.toString()); List<WorkflowRole> roleList = roleTable.selectAllWhere("step", step); System.out.println("Size: "+roleList.size()); return roleList; } public static String getRolesDescription(Database database, String roleName)throws SormulaException{ Table<WorkflowRole> roleTable = database.getTable(WorkflowRole.class); List<WorkflowRole> roleList = roleTable.selectAllCustom("where role=?", roleName); if(roleList.size()==0){ return ""; }else return roleList.get(0).getDescription(); } @Override public String toString() { return "WorkflowRole [id=" + id + ", step=" + step + ", role=" + role + ", description=" + description + "]"; } }
Java
package insight.miescor.opp.domain; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import org.sormula.annotation.Where; import org.sormula.annotation.WhereField; import org.sormula.annotation.Wheres; @Wheres({ @Where(name="stage", whereFields=@WhereField(name="stage", comparisonOperator="=")) }) public class Workflow { private int id; private int stage; private String stagename; private int reject; private String assignment; public String getAssignment() { return assignment; } public void setAssignment(String assignment) { this.assignment = assignment; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getStage() { return stage; } public void setStage(int stage) { this.stage = stage; } public String getStagename() { return stagename; } public void setStagename(String stagename) { this.stagename = stagename; } public int getReject() { return reject; } public void setReject(int reject) { this.reject = reject; } public static Workflow getWorkflowByStage(Database database, int stage)throws SormulaException{ Table<Workflow> workflowTable = database.getTable(Workflow.class); Workflow workflow = workflowTable.select(stage); return workflow; } public static boolean isLastStage(Database database, int stage)throws SormulaException{ Table<Workflow> workflowTable = database.getTable(Workflow.class); Workflow workflow = workflowTable.select(stage+1); if(workflow != null) return false; else return true; } public static boolean isFirstStage(Database database,int stage)throws SormulaException{ Table<Workflow> workflowTable = database.getTable(Workflow.class); Workflow workflow = workflowTable.select(stage); if(workflow.getStage() == 1) return true; else return false; } public static String getStageName(Database database, int stage)throws SormulaException{ Table<Workflow> workflowTable = database.getTable(Workflow.class); Workflow workflow = workflowTable.selectWhere("stage", stage); if(workflow != null){ System.out.println(workflow.toString()); return workflow.getStagename(); } else return "Complete"; } @Override public String toString() { return "Workflow [id=" + id + ", stage=" + stage + ", stagename=" + stagename + ", reject=" + reject + ", assignment=" + assignment + "]"; } }
Java
package insight.miescor.opp.domain; import java.util.Comparator; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Location; public class ILocation { public static final String[] Fields = { "Name", "Country", "CountryCode" }; private int id; private String text; private String country; private String countryCode; public ILocation(Location location) throws BusinessObjectException { setId(location.getObjectId().toInteger()); setText(location.getName()); setCountry(location.getCountry()); setCountryCode(location.getCountryCode()); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public static class ILocationSort implements Comparator<ILocation> { @Override public int compare(ILocation left, ILocation right) { return left.text.compareTo(right.text); } } }
Java
package insight.miescor.opp.domain; import com.google.gson.annotations.SerializedName; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Currency; public class ICurrency { public static final String[] Fields = { "Id", "IsBaseCurrency", "ExchangeRate" }; private String id; private String text; @SerializedName("selected") private boolean isBase; private double excRate; public ICurrency(Currency currency) throws BusinessObjectException { id = currency.getId(); text = id; setBase(currency.getIsBaseCurrency()); excRate = currency.getExchangeRate(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isBase() { return isBase; } public void setBase(boolean isBase) { this.isBase = isBase; } public double getExcRate() { return excRate; } public void setExcRate(double excRate) { this.excRate = excRate; } public double convert(double value) { return value * excRate; } }
Java
package insight.miescor.opp.domain; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; public class AssignmentGrid extends Assignment { private String title; private String projectType; private String initiator; private Date createdOn; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getProjectType() { return projectType; } public void setProjectType(String projectType) { this.projectType = projectType; } public JSONObject getJson() throws JSONException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); JSONObject jObj = new JSONObject() .put("id", this.getId()) .put("opportunityId", this.getOpportunityId()) .put("startDate", this.getStartDate()) .put("endDate", this.getEndDate()) .put("status", this.getStatus()) .put("stepId", this.getStepId()) .put("title", this.getTitle()) .put("type", this.getProjectType()) .put("role", this.getRole()) .put("userId", this.getUserId()) .put("prjObjId", this.getProjectObjId()) .put("Initiator", this.getInitiator()) .put("CreatedOn", (this.getCreatedOn() != null ? sdf.format(this .getCreatedOn()) : "")); return jObj; } public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } }
Java
package insight.miescor.opp.domain; import java.util.Date; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import org.sormula.Database; import org.sormula.SormulaException; import org.sormula.Table; import org.sormula.annotation.Transient; public class Assignment implements Cloneable { private int id; private String opportunityId; private String role; private int projectObjId; private String userId; private String status; private String approvalType; private Date startDate; private Date endDate; private int reviewId; private int stepId; private String outcome; @Transient private Opportunity opportunity; public static int generateId(Database database) throws SormulaException { NumberGenerator numGen = NumberGenerator.loadNextNum(database, "AssignmentId"); return numGen.getSeriesCurrentNum(); } public Assignment() { } public Assignment(String role, String userId, String appType, int reviewId, int stepId, Opportunity oppObj, Database database) throws SormulaException { this.id = generateId(database); this.opportunityId = oppObj.getId(); this.role = role; this.projectObjId = oppObj.getProjectId(); this.userId = userId; this.approvalType = appType; this.reviewId = reviewId; this.stepId = stepId; this.opportunity = oppObj; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOpportunityId() { return opportunityId; } public void setOpportunityId(String opportunityId) { this.opportunityId = opportunityId; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public int getProjectObjId() { return projectObjId; } public void setProjectObjId(int projectObjId) { this.projectObjId = projectObjId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getApprovalType() { return approvalType; } public void setApprovalType(String approvalType) { this.approvalType = approvalType; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getReviewId() { return reviewId; } public void setReviewId(int reviewId) { this.reviewId = reviewId; } public int getStepId() { return stepId; } public void setStepId(int stepId) { this.stepId = stepId; } public Opportunity getOpportunity() { return opportunity; } public void setOpportunity(Opportunity opportunity) { this.opportunity = opportunity; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } public JSONObject getJson() throws JSONException { JSONObject jObj = new JSONObject().put("id", this.getId()) .put("opportunityId", this.getOpportunityId()) .put("startDate", this.getStartDate()) .put("endDate", this.getEndDate()) .put("status", this.getStatus()) .put("stepId", this.getStepId()).put("role", this.getRole()) .put("title", this.getOpportunity().getTitle()) .put("type", this.getOpportunity().getProjectType()); return jObj; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } public void insertAssignment(Database database) throws SormulaException { Table<Assignment> assTable = database.getTable(Assignment.class); assTable.insert(this); } public static Assignment getAssignmentById(Database database, String itemId) throws SormulaException { Table<Assignment> assTable = database.getTable(Assignment.class); Assignment ass = assTable.select(itemId); ass.setOpportunity(Opportunity.getOpportunityById(database, ass.getOpportunityId())); return ass; } public static int getStepId(Database database, String itemId) throws SormulaException { Table<Assignment> assTable = database.getTable(Assignment.class); Assignment ass = assTable.select(itemId); return ass.getStepId(); } public static List<Assignment> getAssignmentDetailByOppId(Database database, String opportunityId) throws SormulaException { Table<Assignment> assTable = database.getTable(Assignment.class); List<Assignment> assList = assTable.selectAllCustom("where opportunityId = ?", opportunityId); //List<Assignment> assList = assTable.selectAllWhereOrdered("opportunityId = ?","StartDate", opportunityId); return assList; } @Override public String toString() { return "Assignment [id=" + id + ", opportunityId=" + opportunityId + ", role=" + role + ", projectObjId=" + projectObjId + ", userId=" + userId + ", status=" + status + ", approvalType=" + approvalType + ", startDate=" + startDate + ", endDate=" + endDate + ", reviewId=" + reviewId + ", stepId=" + stepId + ", outcome=" + outcome + ", opportunity=" + opportunity + "]"; } }
Java
package insight.miescor.opp.domain; import org.json.JSONException; import org.json.JSONObject; public class Users { private String id; private String name; private String emailid; public Users() { } public Users(JSONObject userObj) throws JSONException { id = userObj.has("id") ? userObj.getString("id") : ""; name = userObj.has("name") ? userObj.getString("name") : ""; emailid = userObj.has("sapId") ? userObj.getString("emailid") : ""; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmailid() { return emailid; } public void setEmailid(String emailid) { this.emailid = emailid; } }
Java
package insight.miescor.annotations; public class Constants { public static class UDFDataType{ public static final int TEXT = 0; public static final int START_DATE = 1; public static final int FINISH_DATE = 2; public static final int COST = 3; public static final int DOUBLE = 4; public static final int INTEGER = 5; public static final int INDICATOR = 6; public static final int CODE = 7; } public static class ProjectFields{ public static final String FAV_TERMS="Favourable Terms"; public static final String ADV_TERMS="Adverse Terms"; public static final String REG_REQUIREMENT = "Regulatory Requirements"; public static final String ADD_NOTES = "Additional Notes"; public static final String REG_RATING = "Regulatory Requirements"; public static final String RISK_RATING = "Risk Rating"; public static final String CAPABILITY_ASS = "Res. Availability/Capability Assesment"; public static final String BANDWIDTH = "Band Width / Spare Capacity"; public static final String CAPABILITY = "Capability"; public static final String CONTRACT_VALUE_EX_TAXES="Contract Value (Ex. Taxes)"; public static final String REALIZATION = "Realization"; public static final String FIN_RISK_ASSESMENT = "Risk Assessment"; public static final String FIN_VIABILITY = "Financial Viability"; public static final String FUNDING_DETAILS = "Funding Details"; public static final String CONTRACT_VALUE_RATING = "Contract Value"; public static final String FIN_VIABILITY_RATING = "Financial Viability"; public static final String REALIZATION_RATING = "Realization"; public static final String PROJECT_FUNDING = "Project Funding"; public static final String STRATEGIC_IMP = "Strategic Importance"; public static final String CUSTOMER = "Customer/Consultant"; public static final String ALIGNMENT = "Alignment"; public static final String LOCATION_RATING = "Location"; public static final String BUILD_TRACK = "Builds Track Record"; public static final String MARKET_PENETRATION = "Improves Market Penetration"; public static final String IS_COMPULSIVE_WIN = "Is Compulsive Win?"; public static final String WIN_RATIO = "Maintains/Improves Win Ratio"; public static final String TYPE_OF_WORK = "Type of Work"; public static final String CUSTOMER_RATING = "Customer"; public static final String CONSULTANT_RATING = "Consultant Rating"; public static final String WINNABILITY = "Winnability"; public static final String PRJ_DESCRIPTION = "Description"; public static final String JV_DETAILS = "JV Details"; public static final String RISK_SYNOPSIS = "Risk Synopsis"; public static final String COMPETITVE_ANALYSIS = "Competitive Analysis"; public static final String ADD_NOTES_ON_TIMELINE = "Additional Notes on Timeline"; public static final String MARKET = "Market "; public static final String PORTFOLIO = "Portfolios"; public static final String PROJECT_TYPE = "Project Type"; public static final String PACKAGE_NAME = "Package Name"; public static final String CONTRACT_NUMBER = "Contract Number"; public static final String CUSTOMER_NAME = "Customer"; public static final String IS_JV = "Is Joint Venture?"; public static final String BID_DATE = "Bid Submission By"; public static final String AWARD_DATE = "Award Date"; public static final String PRJ_START_DATE = "Project Start Date"; public static final String PROJECT_DURTION = "Project Duration"; public static final String NOTEBOOK_CONTRACT_VALUE = "Contract Value"; public static final String INITIATOR = "Initiator"; public static final String UDF_CONTRACT_VALUE = "Contract Value"; public static final String UDF_AWARD_DATE = "Award Date"; } }
Java
package insight.miescor.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Notebook { String topicName(); boolean append() default false; }
Java
package insight.miescor.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UDF { String name(); int dataType(); }
Java
package insight.miescor.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Code { String name(); }
Java
package insight.miescor.db; import insight.common.Encrypter; import insight.common.logging.JLogger; import insight.miescor.opp.domain.AssignmentGrid; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.sormula.Database; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class DBManager { private Database database; private Connection connection; private static Logger logger = JLogger.getLogger("StratupLog"); private DriverManagerDataSource dataSource; private JdbcTemplate template; public DBManager(String driver, String url, String user, String password) { try { Class.forName(driver); System.out.println("URL : " + url); System.out.println("user : " + user); System.out.println("password : " + password); connection = DriverManager.getConnection(url, user, password); database = new Database(connection); dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(decrypt(password)); template = new JdbcTemplate(dataSource); System.out.println("connect"); } catch (ClassNotFoundException e) { logger.log(Level.SEVERE, "Application startup failed, driver class " + driver + " could not be loaded.", e); } catch (SQLException e) { logger.log(Level.SEVERE, "Application startup failed, connection to db failed.", e); } } private String decrypt(String inStr) { try { return Encrypter.decrypt(inStr); } catch (Exception ex) { } return inStr; } public Database getDatabase() { return database; } @SuppressWarnings("unchecked") public List<AssignmentGrid> getAssignmentList(String[] status, String[] roles) { List<AssignmentGrid> listAssignmentBeans = new ArrayList<AssignmentGrid>(); AssignmentMapper newMapper = new AssignmentMapper(); String sql = "Select Assignment.id,Assignment.opportunityid, Assignment.startdate,Assignment.enddate,Assignment.status,"; sql += " Assignment.stepid,Assignment.role,opportunity.title,opportunity.projecttype,Assignment.userId,Assignment.ProjectObjId,"; sql += " opportunity.initiator,opportunity.createdOn from Assignment inner Join opportunity on "; sql += " Assignment.opportunityid= opportunity.id where Assignment.status in "; sql += getStringInClause(status) + " And Assignment.role in " + getStringInClause(roles); // System.out.println(sql); listAssignmentBeans = (List<AssignmentGrid>) template.query(sql, newMapper); // logger.fine(sql); return listAssignmentBeans; } @SuppressWarnings("unchecked") public List<AssignmentGrid> getClaimedAssignmentList(String[] status, String[] roles, String userId) { List<AssignmentGrid> listAssignmentBeans = new ArrayList<AssignmentGrid>(); AssignmentMapper newMapper = new AssignmentMapper(); String sql = "Select Assignment.id,Assignment.opportunityid, Assignment.startdate,Assignment.enddate,Assignment.status,"; sql += " Assignment.stepid,Assignment.role,opportunity.title,opportunity.projecttype,Assignment.userId,Assignment.ProjectObjId, "; sql += " opportunity.initiator,opportunity.createdOn from Assignment inner Join opportunity on "; sql += " Assignment.opportunityid= opportunity.id where Assignment.status in "; sql += getStringInClause(status) + " And Assignment.role in " + getStringInClause(roles); sql += " And Assignment.userId in ('" + userId + "')"; listAssignmentBeans = (List<AssignmentGrid>) template.query(sql, newMapper); // logger.fine(sql); return listAssignmentBeans; } public String getStringInClause(String[] ary) { String clause = "("; for (String st : ary) { clause += "'" + st + "',"; } if (clause.lastIndexOf(",") > 0) clause = clause.substring(0, clause.lastIndexOf(",")); clause += ") "; return clause; } public JdbcTemplate getTemplate() { return template; } public void setTemplate(JdbcTemplate template) { this.template = template; } }
Java
package insight.miescor.db; import insight.miescor.opp.domain.AssignmentGrid; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class AssignmentMapper implements RowMapper { public AssignmentGrid mapRow(ResultSet res, int arg1) throws SQLException { AssignmentGrid beanObj = new AssignmentGrid(); beanObj.setId(res.getInt("id")); beanObj.setOpportunityId(res.getString("opportunityId")); beanObj.setStartDate(res.getDate("startDate")); beanObj.setEndDate(res.getDate("endDate")); beanObj.setStatus(res.getString("Status")); beanObj.setStepId(res.getInt("stepId")); beanObj.setRole(res.getString("role")); beanObj.setUserId(res.getString("userId")); beanObj.setTitle(res.getString("title")); beanObj.setProjectType(res.getString("projecttype")); beanObj.setProjectObjId(res.getInt("ProjectObjId")); beanObj.setInitiator(res.getString("Initiator")); beanObj.setCreatedOn(res.getDate("CreatedOn")); return beanObj; } }
Java
package insight.p6.event; import insight.common.PropertyLoader; import insight.common.logging.JLogger; import insight.primavera.common.P6helper; import insight.primavera.common.Utils; import java.io.StringReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.TextMessage; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.springframework.beans.factory.annotation.Autowired; import primavera.events.v83.ActivityUpdatedType; import primavera.events.v83.MessagingObjects; import com.primavera.common.value.ObjectId; import com.primavera.integration.client.bo.BOIterator; import com.primavera.integration.client.bo.enm.ActivityType; import com.primavera.integration.client.bo.enm.UDFIndicator; import com.primavera.integration.client.bo.enm.UDFSubjectArea; import com.primavera.integration.client.bo.object.Activity; import com.primavera.integration.client.bo.object.ActivityCodeAssignment; /** * This example shows how to establish a connection to and receive messages from * a JMS queue. The classes in this package operate on the same JMS queue. Run * the classes together to witness messages being sent and received, and to * browse the queue for messages. This class is used to receive and remove * messages from the queue. * * @author Copyright (c) 1999-2005 by BEA Systems, Inc. All Rights Reserved. */ public class QueueReceive implements MessageListener { static final Logger logger = JLogger .getLogger(QueueReceive.class.getName()); @Autowired private P6helper helper; // // Defines the JNDI context factory. // public final static String JNDI_FACTORY = // "weblogic.jndi.WLInitialContextFactory"; // // // Defines the JMS connection factory for the queue. // public final static String JMS_FACTORY = PropertyLoader.getProperty( // "jms.connection.name", "jms/P6ConnectionFactory"); // // // Defines the queue. // public final static String QUEUE = PropertyLoader.getProperty( // "jms.queue.name", "jms/PrimaveraQ"); // // private QueueConnectionFactory qconFactory; // private QueueConnection qcon; // private QueueSession qsession; // private QueueReceiver qreceiver; // private Queue queue; // private boolean quit = false; // public QueueReceive() throws Exception { // main(new String[]{""}); // } /** * Message listener interface. * * @param msg * message */ public void onMessage(Message msg) { try { String msgText = ""; if (msg instanceof TextMessage) { msgText = ((TextMessage) msg).getText(); logger.info("Message Received : " + msgText); try { logger.fine("Creating Messaging Object"); JAXBContext jc = JAXBContext .newInstance(MessagingObjects.class); Unmarshaller u = jc.createUnmarshaller(); Object obj = u.unmarshal(new StringReader(msgText)); MessagingObjects msgObj = (MessagingObjects) obj; ActivityUpdatedType updObj; logger.fine("Check whether its activity updated event"); if ((updObj = msgObj.getActivityUpdated()) != null) { logger.info("A primavera activity updated."); updateProjectIndicator(helper.getSession(), updObj.getObjectId()); } } catch (JAXBException e) { logger.log(Level.SEVERE, e.getMessage(), e); e.printStackTrace(); } } // System.out.println("Message Received: " + msgText); // if (msgText.equalsIgnoreCase("quit")) { // synchronized (this) { // quit = true; // this.notifyAll(); // Notify main thread to quit // } // } } catch (JMSException jmse) { logger.log(Level.SEVERE, jmse.getMessage(), jmse); } } // /** // * Creates all the necessary objects for receiving messages from a JMS // * queue. // * // * @param ctx // * JNDI initial context // * @param queueName // * name of queue // * @exception NamingException // * if operation cannot be performed // * @exception JMSException // * if JMS fails to initialize due to internal error // */ // public void init(Context ctx, String queueName) throws NamingException, // JMSException { // qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); // qcon = qconFactory.createQueueConnection(); // qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); // queue = (Queue) ctx.lookup(queueName); // qreceiver = qsession.createReceiver(queue); // qreceiver.setMessageListener(this); // qcon.start(); // } // // /** // * Closes JMS objects. // * // * @exception JMSException // * if JMS fails to close objects due to internal error // */ // public void close() throws JMSException { // qreceiver.close(); // qsession.close(); // qcon.close(); // } /** * main() method. * * @param args * WebLogic Server URL * @exception Exception * if execution fails */ // public static void main(String[] args) throws Exception { // // System.setProperty("insight.application.config", // // "F:\\Workspaces\\Miescore\\P6MessageQueue"); // // System.setProperty("primavera.bootstrap.home", // // "F:\\Workspaces\\Miescore\\P6MessageQueue\\properties"); // // // // // P6helper helper = new P6helper(); // // com.primavera.integration.client.Session session = // // helper.getSession(); // // // // if(session==null){ // // System.out.println("Session null"); // // } // // System.exit(0); // // String serverURL = PropertyLoader.getProperty( // "primavera.queue.serverurl", "t3://172.17.71.23:7001"); // InitialContext ic = getInitialContext(serverURL); // QueueReceive qr = new QueueReceive(); // qr.init(ic, QUEUE); // // System.out // .println("JMS Ready To Receive Messages (To quit, send a \"quit\" message)."); // // // Wait until a "quit" message has been received. // synchronized (qr) { // while (!qr.quit) { // try { // qr.wait(); // } catch (InterruptedException ie) { // } // } // } // qr.close(); // } // // @SuppressWarnings("unchecked") // private static InitialContext getInitialContext(String url) // throws NamingException { // Hashtable env = new Hashtable(); // env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); // env.put(Context.PROVIDER_URL, url); // return new InitialContext(env); // } public static void updateProjectIndicator( com.primavera.integration.client.Session session, int activityObjId) { // P6helper helper = new P6helper(); try { logger.info("Loading activity object Id : " + activityObjId); Activity activity = Activity.load(session, new String[] { "Id", "ProjectObjectId", "Type", "ActualFinishDate" }, new ObjectId(activityObjId)); logger.fine("Check whether activity is FINISH MILESTONE Type"); if (activity.getType() == ActivityType.FINISH_MILESTONE || activity .getType() == ActivityType.MILESTONE) { String where = "ActivityCodeTypeName='" + PropertyLoader.getProperty( "primavera.milestone.codename", "Drives") + "'"; logger.info("Loading Activity Code Assignment where " + where); BOIterator<ActivityCodeAssignment> itr = activity .loadActivityCodeAssignments( new String[] { "ActivityCodeValue" }, where, null); if (itr.hasNext()) { ActivityCodeAssignment actAssign = itr.next(); logger.fine("Getting Activity Code Value"); String codeValue = actAssign.getActivityCodeValue(); logger.fine("Getting Activity ProjectObjectId."); ObjectId prjObjId = activity.getProjectObjectId(); logger.info("Code value" + codeValue + " ProjectObjectId : " + prjObjId); logger.info("Set UDF value [" + codeValue + "Status" + "] on project"); Utils.setUDFValueIndicator(session, UDFSubjectArea.PROJECT, codeValue + " Status", prjObjId, UDFIndicator.GREEN); logger.info("Set UDF value [" + codeValue + "Date" + "] on project"); Utils.setUDFValueDate(session, UDFSubjectArea.PROJECT, codeValue + " Date", prjObjId, activity.getActualFinishDate()); } } } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } } public P6helper getHelper() { return helper; } public void setHelper(P6helper helper) { this.helper = helper; } }
Java
package insight.p6.event; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * This example shows how to establish a connection and send messages to the JMS * queue. The classes in this package operate on the same JMS queue. Run the * classes together to witness messages being sent and received, and to browse * the queue for messages. The class is used to send messages to the queue. * * @author Copyright (c) 1999-2005 by BEA Systems, Inc. All Rights Reserved. */ public class QueueSend { // Defines the JNDI context factory. public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory"; // Defines the JMS context factory. public final static String JMS_FACTORY = "jms/P6ConnectionFactory"; // Defines the queue. public final static String QUEUE = "jms/P6Queue"; private QueueConnectionFactory qconFactory; private QueueConnection qcon; private QueueSession qsession; private QueueSender qsender; private Queue queue; private TextMessage msg; /** * Creates all the necessary objects for sending messages to a JMS queue. * * @param ctx * JNDI initial context * @param queueName * name of queue * @exception NamingException * if operation cannot be performed * @exception JMSException * if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue) ctx.lookup(queueName); qsender = qsession.createSender(queue); msg = qsession.createTextMessage(); qcon.start(); } /** * Sends a message to a JMS queue. * * @param message * message to be sent * @exception JMSException * if JMS fails to send message due to internal error */ public void send(String message) throws JMSException { msg.setText(message); qsender.send(msg); } /** * Closes JMS objects. * * @exception JMSException * if JMS fails to close objects due to internal error */ public void close() throws JMSException { qsender.close(); qsession.close(); qcon.close(); } /** * main() method. * * @param args * WebLogic Server URL * @exception Exception * if operation fails */ public static void main(String[] args) throws Exception { String serverURL = "t3://172.17.71.23:7001"; InitialContext ic = getInitialContext(serverURL); QueueSend qs = new QueueSend(); qs.init(ic, QUEUE); readAndSend(qs); qs.close(); } private static void readAndSend(QueueSend qs) throws IOException, JMSException { BufferedReader msgStream = new BufferedReader(new InputStreamReader( System.in)); String line = null; boolean quitNow = false; do { System.out.print("Enter message (\"quit\" to quit): \n"); line = msgStream.readLine(); if (line != null && line.trim().length() != 0) { qs.send(line); System.out.println("JMS Message Sent: " + line + "\n"); quitNow = line.equalsIgnoreCase("quit"); } } while (!quitNow); } private static InitialContext getInitialContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); env.put(Context.PROVIDER_URL, url); return new InitialContext(env); } }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.io.IOUtils; public class CustomerSelTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String incTiny; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); InputStream in = this.getClass().getClassLoader() .getResourceAsStream("customersel.inc"); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String outStr = writer.toString(); in.close(); writer.close(); out.println(outStr); } catch (IOException e) { e.printStackTrace(); } return SKIP_BODY; } public String getIncTiny() { return incTiny; } public void setIncTiny(String incTiny) { this.incTiny = incTiny; } }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class ButtonTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String id; private String title; private String style; private String onclick; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); String onclickStr = onclick != null ? "onclick=\"" + onclick + "\"" : ""; String strOut = "<a id=\"" + id + "\" href=\"javascript:void(0)\" " + "class=\"easyui-linkbutton\"" + onclickStr + ">" + title + "</a>"; out.println(strOut); } catch (IOException e) { e.printStackTrace(); } return SKIP_BODY; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getOnclick() { return onclick; } public void setOnclick(String onclick) { this.onclick = onclick; } }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class FormTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String id; private String title; private String style; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); String startTag = "<div class=\"easyui-panel formBody\"\n" + " data-options=\"headerCls:'formHeader',bodyCls:'formBody'\"\n" + " title=\"" + (title != null ? title : "") + "\"" + (style != null ? style : "") + ">\n" + "\t<form id=\"" + id + "\" method=\"post\">"; out.println(startTag); } catch (IOException e) { e.printStackTrace(); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.println("\t</form>\n</div>"); } catch (IOException e) { e.printStackTrace(); } return EVAL_PAGE; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; }; }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.io.IOUtils; public class LocationSelTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String incTiny; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); InputStream in = this.getClass().getClassLoader() .getResourceAsStream("locationsel.inc"); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String outStr = writer.toString(); in.close(); writer.close(); out.println(outStr); } catch (IOException e) { e.printStackTrace(); } return SKIP_BODY; } public String getIncTiny() { return incTiny; } public void setIncTiny(String incTiny) { this.incTiny = incTiny; } }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.io.IOUtils; public class PageHeaderTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String incTiny; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); InputStream in = this.getClass().getClassLoader() .getResourceAsStream("jquery.inc"); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String headerStr = writer.toString(); in.close(); writer.close(); if (incTiny != null && incTiny.equalsIgnoreCase("yes")) { in = this.getClass().getClassLoader() .getResourceAsStream("tinymce.inc"); writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); headerStr += "\n" + writer.toString(); } out.println(headerStr); } catch (IOException e) { e.printStackTrace(); } return SKIP_BODY; } public String getIncTiny() { return incTiny; } public void setIncTiny(String incTiny) { this.incTiny = incTiny; } }
Java
package insight.jsp.custom.taglib; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.io.IOUtils; public class AttributeTagHandler extends TagSupport { private static final long serialVersionUID = 1L; private String id; private String type; private String required; private String title; private String style; private String code; @Override public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); String strOut = buildOutput(); out.println(strOut); } catch (IOException e) { e.printStackTrace(); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { JspWriter out = pageContext.getOut(); String strOut = ""; if (type != null && type.equalsIgnoreCase("combo")) { strOut = "</select>"; } strOut += "</td></tr>"; out.println(strOut); } catch (IOException e) { e.printStackTrace(); } return EVAL_PAGE; } private String buildOutput() { String strOut = "<tr style=\"\"><td><b>" + title + ":</b></td><td>"; if (type.equalsIgnoreCase("addNotes")) { strOut = "<tr style=\"\"><td><b>" + title + ":</b><br><a id=\"btnShowAddComments\" onclick=\"showAddComments();\">Show Existing Comments</a></td><td>"; } String reqStr = required != null && required.equalsIgnoreCase("yes") ? " data-options=\"required:true\"" : ""; String styleStr = style != null ? " style=\"" + style + "\"" : ""; String idStr = " name=\"" + id + "\"" + " id=\"" + id + "\""; if (type == null || type.equalsIgnoreCase("text")) { if (code == null || !code.equalsIgnoreCase("yes")) { strOut += "<input class=\"easyui-validatebox textbox\" type=\"text\"" + idStr + reqStr + styleStr + "></input>"; } else { strOut += readFromFile("codetag.inc", styleStr, reqStr); } } else if (type.equalsIgnoreCase("textarea")) { strOut += "<textarea" + idStr + styleStr + "></textarea>"; } else if (type.equalsIgnoreCase("combo")) { strOut += "<select class=\"easyui-combobox\" " + idStr + " data-options=\"editable:false\">"; } else if (type.equalsIgnoreCase("date")) { strOut += "<input class=\"easyui-datebox\" " + idStr + reqStr + styleStr + "></input>"; } else if (type.equalsIgnoreCase("number")) { strOut += "<input class=\"easyui-numberbox\"" + "data-options=\"precision:2,groupSeparator:','\"" + idStr + reqStr + styleStr + "/>"; } else if (type.equalsIgnoreCase("cost")) { strOut += readFromFile("costtag.inc", styleStr, reqStr); } else if (type.equalsIgnoreCase("p6code") && code != null) { try { code = URLEncoder.encode(code, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } strOut += "<select class=\"easyui-combotree\" data-options=\"url:'loadProjectCode.htm?code=" + code + "'" + (required != null && required == "yes" ? ", required:true" : "") + "\"" + styleStr + idStr + "></select>"; } else if (type.equalsIgnoreCase("addNotes")) { strOut += "<textarea" + idStr + styleStr + "></textarea>"; } return strOut; } public String readFromFile(String fileName, CharSequence styleStr, CharSequence reqStr) { InputStream in = this.getClass().getClassLoader() .getResourceAsStream(fileName); StringWriter writer = new StringWriter(); try { IOUtils.copy(in, writer, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } String strOut = writer.toString(); strOut = strOut.replace("{id}", id).replace("{reqStr}", "required"); return strOut; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRequired() { return required; } public void setRequired(String required) { this.required = required; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
Java
import insight.miescor.annotations.Code; import insight.miescor.db.DBManager; import insight.miescor.opp.domain.Assignment; import insight.miescor.opp.domain.CodeValue; import insight.primavera.common.P6helper; import insight.web.delegates.AjaxJSONDelegate; import insight.web.delegates.PrimaveraDelegate; import java.sql.CallableStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import org.sormula.SormulaException; import com.primavera.ServerException; import com.primavera.bo.schema.client.UserObs; import com.primavera.common.value.ObjectId; import com.primavera.integration.client.EnterpriseLoadManager; import com.primavera.integration.client.Session; import com.primavera.integration.client.bo.BOIterator; import com.primavera.integration.client.bo.BusinessObjectException; import com.primavera.integration.client.bo.object.Location; import com.primavera.integration.client.bo.object.OBS; import com.primavera.integration.client.bo.object.Project; import com.primavera.integration.client.bo.object.ProjectCode; import com.primavera.integration.client.bo.object.ProjectCodeType; import com.primavera.integration.client.bo.object.UserOBS; import com.primavera.integration.common.rmi.Utils; import com.primavera.integration.network.NetworkException; public class TestStub { public static class table { @Code(name = "Project Name") private String prjName; @Code(name = "Project ID") private String ProjectID; public String getPrjName() { return prjName; } public void setPrjName(String prjName) { this.prjName = prjName; } public String getProjectID() { return ProjectID; } public void setProjectID(String projectID) { ProjectID = projectID; } } public static void main(String[] args) throws SQLException, NoSuchMethodException, SormulaException, BusinessObjectException, ServerException, NetworkException { // DBManager dbManager = new DBManager("oracle.jdbc.OracleDriver", // "jdbc:oracle:thin:@172.17.71.21:1563:dbmcordv", "p6ext", // "oracle"); // List<Assignment> lstass= // Assignment.getAssignmentDetailByOppId(dbManager.getDatabase(),"03O14-0008"); // for(Assignment ass:lstass){ // System.out.println(ass.getId()); // } // System.exit(0); System.setProperty("insight.application.config", "F:\\Workspaces\\Miescore\\P6Extensions"); System.setProperty("primavera.bootstrap.home", "F:\\Workspaces\\Miescore\\P6Extensions\\properties"); P6helper helper = new P6helper(); setProjectOBS(helper, "02P14-0012"); // readOBS(helper); System.exit(0); // Location location = new Location(helper.getSession()); // location.setName("testLoc1"); // // location.setCountryCode("US"); // // location.setLatitude(0); // location.setLongitude(0); // ObjectId locId = location.create(); // Session session=helper.getSession(); // EnterpriseLoadManager elm = helper.getSession() // .getEnterpriseLoadManager(); // BOIterator<ProjectCode> codeItr = elm.loadProjectCodes( // new String[] { "Description","CodeValue" }, // "CodeValue='Opportunity'", null); // while(codeItr.hasNext()){ // ProjectCode code=codeItr.next(); // System.out.println(code.getDescription()); // } // PrimaveraDelegate.assignProjectCode(session, project, codeId) // String customSql = // "Where Assignment.status in('Pending') and Role in ('PMO') "; // Table<Assignment> assTable = dbManager.getDatabase().getTable( // Assignment.class); // List<Assignment> assignments = assTable.selectAllCustom(customSql); // for (Assignment assignment : assignments) { // // System.out.println(assignment.getId() + " " // // + assignment.getOpp().getUserId()); // } // String insertStoreProc = "{call insertDBUSER(?,?,?,?)}"; // CallableStatement callableStatement = // dbManager.getDatabase().getConnection().prepareCall(insertStoreProc); // // // PreparedStatement statement ;//= // dbManager.getDatabase().getConnection().prepareStatement("SELECT * FROM TblTest"); // // // String sql = "INSERT INTO tblTest (id, userId,amt) " + // // " VALUES (?, ?,?)"; // // //statement= // dbManager.getDatabase().getConnection().prepareStatement(sql); // // Object obj[]=new Object[]{4,"aman",null}; // // // // dbManager.getTemplate().update(sql, obj); // // // // // // // // statement = // dbManager.getDatabase().getConnection().prepareStatement("SELECT * FROM TblTest"); // ResultSet rs = statement.executeQuery(); // // // ResultSetMapper<TblTest> resultSetMapper = new // ResultSetMapper<TblTest>(); // // // // List<TblTest> roleList = resultSetMapper.mapRersultSetToObject1(rs, // TblTest.class); // // for(TblTest role:roleList){ // System.out.println(role.toString()); // } // // // TblTest test=new TblTest(); // test.setId(5); // test.setName("ajay"); // // resultSetMapper.buildSqlForInsert(test); // // System.exit(0); // // // // System.out.println(table.class.isAnnotationPresent(Code.class)); // // for(Field str:table.class.getDeclaredFields()){ // // System.out.println(str.getName()); // // } // // // // Field[] projectCodeFields = // ReflectionDelegate.getAnnotatedFields(table.class, Code.class); // // for (Field projectCodeField : projectCodeFields) { // // // System.out.println(projectCodeField.getAnnotation(Code.class).name()); // // } // // DBManager dbManager = new DBManager("oracle.jdbc.OracleDriver", // // "jdbc:oracle:thin:@172.17.71.21:1563:dbmcordv", "p6ext", // // "oracle"); // // // // JdbcTemplate template = dbManager.getTemplate(); // // SqlRowSet rs = template.queryForRowSet("select * from roles"); // // String[] cols = rs.getMetaData().getColumnNames(); // // TestStub tStub=new TestStub(); // // // // // // while (rs.next()) { // // // // for (String colName : cols) { // // // // } // // } } private static void setProjectOBS(P6helper helper, String string) throws BusinessObjectException, ServerException, NetworkException { Project prj = Project.load(helper.getSession(), Project.getMainFields(), new ObjectId(5507)); // prj.setOBSObjectId(new ObjectId(1874)); // prj.update(); Object ob=prj.getOBSName(); System.out.println(prj.getName() + " OBS -> " + ob); } private static void readOBS(P6helper helper) throws BusinessObjectException, ServerException, NetworkException { getOBSList(helper, "Proposal Managers"); // EnterpriseLoadManager elm = helper.getSession() // .getEnterpriseLoadManager(); // BOIterator<OBS> obsItr = elm.loadOBS(OBS.getAllFields(), // "Name='Proposal Managers'", null); // while (obsItr.hasNext()) { // OBS ob = obsItr.next(); // System.out.println(ob.getName()); // BOIterator<UserOBS> userItr = ob.loadUserOBS( // UserOBS.getAllFields(), "OBSObjectId='" + ob.getObjectId() // + "'", null); // while (userItr.hasNext()) { // UserOBS uObjs = userItr.next(); // System.out.println("\t" + uObjs.getUserName() // + ", OBSName -> " + uObjs.getOBSName()); // // } // // // BOIterator<OBS> childObsItr = ob.loadOBSChildren( // // OBS.getAllFields(), null, null); // // while (childObsItr.hasNext()) { // // OBS ob1 = childObsItr.next(); // // System.out.println("Child OBS -> " + ob1.getName()); // // } // // } } private static List<CodeValue> getOBSUser(P6helper helper, String OBSName) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = helper.getSession() .getEnterpriseLoadManager(); BOIterator<UserOBS> userObsItr = elm.loadUserOBS(new String[] { "OBSName", "UserName", "OBSObjectId", "UserObjectId" }, "OBSName='" + OBSName + "'", null); List<CodeValue> userList = new ArrayList<CodeValue>(); while (userObsItr.hasNext()) { UserOBS userOb = userObsItr.next(); userList.add(new CodeValue(userOb.getUserObjectId().toInteger(), userOb.getUserName())); } return userList; } private static List<CodeValue> getOBSList(P6helper helper, String parentOBSName) throws BusinessObjectException, ServerException, NetworkException { EnterpriseLoadManager elm = helper.getSession() .getEnterpriseLoadManager(); BOIterator<OBS> obsItr = elm.loadOBS( new String[] { "ObjectId", "Name" }, "Name='" + parentOBSName + "'", null); List<CodeValue> obsList = new ArrayList<CodeValue>(); while (obsItr.hasNext()) { OBS ob = obsItr.next(); // System.out.println(ob.getName()); getChildOBS(helper.getSession(), ob, obsList); } for (CodeValue v : obsList) { System.out.println(v.getValue() + " " + v.getId()); } return null; } private static void getChildOBS(Session session, OBS obs, List<CodeValue> obsList) throws BusinessObjectException, ServerException, NetworkException { // System.out.println("Adding " + obs.getName()); obsList.add(new CodeValue(obs.getObjectId().toInteger(), obs.getName())); BOIterator<OBS> obsItr = obs.loadOBSChildren(new String[] { "ObjectId", "Name" }, null, null); while (obsItr.hasNext()) { OBS ob = obsItr.next(); getChildOBS(session, ob, obsList); } } // public static class Table { // private List<Row> rows; // public Table(){ // // } // private void addRow(Row row) { // rows.add(row); // } // // public List<Row> getRows() { // return rows; // } // // public void setColumns(List<Row> rows) { // this.rows = rows; // } // // } // // public class Row { // private List<Column> columns; // // public void addColumn(Column column) { // this.columns.add(column); // } // // public List<Column> getColumns() { // return columns; // } // // public void setColumns(List<Column> columns) { // this.columns = columns; // } // } // // public class Column { // @Attribute("colName=firstName") // private String colName; // private String colValue; // // public Column(String colName, String colValue) { // this.colName = colName; // this.colValue = colValue; // } // // public String getColName() { // return colName; // } // // public void setColName(String colName) { // this.colName = colName; // } // // public String getColValue() { // return colValue; // } // // public void setColValue(String colValue) { // this.colValue = colValue; // } // } }
Java
package insight.web.delegates; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONStringer; /** * * AjaxJSONDelegate class set json object in HttpServletResponse and send back * to the UI. * */ public class AjaxJSONDelegate { /** * * @param jarray * holds the response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONArray jarray, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jarray.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param content * holds the response values * @param res * is HttpServletResonse. */ public static void setTextResponse(final String content, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(content); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param jsonStringer * holds response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONStringer jsonStringer, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jsonStringer.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void setResponse(final JSONObject obj, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); // System.out.print(obj.toString()); w.write(obj.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
Java
package insight.app.config.mvc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "insight.sm.controllers" }) public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/resources/").setCachePeriod(31556926); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { super.addViewControllers(registry); } }
Java
package insight.app.config.mvc; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; //return new Class[]{RootConfiguration.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebMvcConfiguration.class }; } @Override protected String[] getServletMappings() { return new String[] { "*.htm" }; } }
Java
package insight.app.config; import insight.sm.dao.AssignmentsDAOImpl; import insight.sm.dao.IAssignmentsDAO; import insight.sm.dao.IEquipmentDAO; import insight.sm.dao.EquipmentDAOImpl; import insight.sm.dao.ILabourResourcesDAO; import insight.sm.dao.IMaterialDAO; import insight.sm.dao.IProjectDAO; import insight.sm.dao.LabourResourcesDAOImpl; import insight.sm.dao.MaterialDAOImpl; import insight.sm.dao.ProjectDAOImpl; import insight.sm.dao.ITaskDAO; import insight.sm.dao.TaskDAOImpl; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class DAOConfig { @Bean(autowire = Autowire.BY_NAME) public IProjectDAO projectDAO(){ IProjectDAO projectDAO = new ProjectDAOImpl(); System.out.println("instantiating ProjectDAO"); return projectDAO; } @Bean(autowire = Autowire.BY_NAME) public ITaskDAO taskDAO(){ ITaskDAO taskDAO = new TaskDAOImpl(); System.out.println("instantiating TaskDAO"); return taskDAO; } @Bean(autowire = Autowire.BY_NAME) public IEquipmentDAO equipmentDAO(){ IEquipmentDAO equipmentDAO = new EquipmentDAOImpl(); System.out.println("instantiating EquipmentDAO"); return equipmentDAO; } @Bean(autowire = Autowire.BY_NAME) public IAssignmentsDAO assignmentsDAO(){ IAssignmentsDAO assignmentsDAO = new AssignmentsDAOImpl(); System.out.println("instantiating AssignmentDAO"); return assignmentsDAO; } @Bean(autowire = Autowire.BY_NAME) public ILabourResourcesDAO labourResourcesDAO(){ ILabourResourcesDAO labourResourcesDAO = new LabourResourcesDAOImpl(); System.out.println("instantiating LabourResourcesDAO"); return labourResourcesDAO; } @Bean(autowire = Autowire.BY_NAME) public IMaterialDAO materialDAO(){ IMaterialDAO materialDAO = new MaterialDAOImpl(); System.out.println("instantiating MaterialDAO"); return materialDAO; } }
Java
package insight.app.config; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration @Import({DAOConfig.class, ControllerConfig.class}) @ComponentScan @PropertySource("classpath:dao.properties") public class RootConfiguration { @Autowired private Environment environment; @Bean public DataSource dataSource() { System.out.println("instantiating datasource"); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getProperty("db.driver")); dataSource.setUrl(environment.getProperty("db.url")); dataSource.setUsername(environment.getProperty("db.user")); dataSource.setPassword(environment.getProperty("db.password")); return dataSource; } @Bean public JdbcTemplate jdbcTemplate(){ System.out.println("instantiating template"); JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource()); return jdbcTemplate; } @Bean public JavaMailSenderImpl javaMailSenderImpl(){ System.out.println("instantiating mailSender"); JavaMailSenderImpl javaMailSenderImpl=new JavaMailSenderImpl(); javaMailSenderImpl.setHost(environment.getProperty("mail.host")); javaMailSenderImpl.setPort(Integer.parseInt(environment.getProperty("mail.port"))); javaMailSenderImpl.setUsername(environment.getProperty("mail.username")); javaMailSenderImpl.setPassword(environment.getProperty("mail.password")); Properties javaMailProperties=new Properties(); javaMailProperties.setProperty(environment.getProperty("mail.auth"),environment.getProperty("mail.auth.value")); javaMailProperties.setProperty(environment.getProperty("mail.ttls"),environment.getProperty("mail.ttls.value")); javaMailProperties.setProperty(environment.getProperty("mail.trust"),environment.getProperty("mail.trust.value")); javaMailProperties.setProperty(environment.getProperty("mail.debug"),environment.getProperty("mail.debug.value")); javaMailSenderImpl.setJavaMailProperties(javaMailProperties); return javaMailSenderImpl; } }
Java
package insight.app.config; import org.springframework.context.annotation.Configuration; @Configuration public class ControllerConfig { }
Java
package insight.app.config.security; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity @ComponentScan(basePackages = "insight.app.config") public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public DataSource dataSource; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("nsbassi").password("a") .roles("USER", "MANAGER", "ADMIN"); // auth.jdbcAuthentication().dataSource(dataSource) // .usersByUsernameQuery("select username,password,enabled from users where username = ?") // .authoritiesByUsernameQuery("select username,authority from authorities where username = ?"); } }
Java
package insight.app.config.security; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { public SecurityWebApplicationInitializer() { super(SecurityConfig.class); } }
Java
package insight.sm.constants; public class Constants { public static class Session { public static final String CURRENT_USER_NAME = null; public static final String CURRENT_USER_ID = null; } public enum ProjectStatusConstants { PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D"); private String statusCode; private ProjectStatusConstants(String s) { statusCode = s; } public String getProjectStatusConstants() { return statusCode; } } public enum TaskStatusConstants { PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D"); private String statusCode; private TaskStatusConstants(String s) { statusCode = s; } public String getTaskStatusConstants() { return statusCode; } } }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialIssue; public interface IMaterialIssueDAO extends IGenericDAO<MaterialIssue> { }
Java
package insight.sm.dao; import insight.sm.pojo.Task; public class TaskDAOImpl extends GenericDAOImpl<Task> implements ITaskDAO{ }
Java
package insight.sm.dao; import insight.sm.db.EntityRowMapper; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; public abstract class GenericDAOImpl<T> implements IGenericDAO<T> { @Autowired private JdbcTemplate jdbcTemplate; public int insertRecord(T instance) { try{ @SuppressWarnings("rawtypes") Class c=Class.forName(instance.getClass().getName()); LinkedList<String> argumentName=new LinkedList<String>(); LinkedList<String> argumentVal=new LinkedList<String>(); LinkedList<String> argumentType=new LinkedList<String>(); LinkedList<String> placeHolder=new LinkedList<String>(); Field[] fields=instance.getClass().getDeclaredFields(); for(Field field:fields){ if(field.getAnnotation(Column.class)!=null){ if(field.getAnnotation(Column.class).unique()==true){ } else if (field.getAnnotation(Column.class).insertable()==false){ } else if (field.getAnnotation(Column.class).name().length()>0){ argumentName.add(field.getAnnotation(Column.class).name()); placeHolder.add("?"); argumentVal.add(PropertyUtils.getProperty(instance, field.getName()).toString()); argumentType.add(PropertyUtils.getPropertyType(instance, field.getName()).toString()); } else { argumentName.add(field.getName()); placeHolder.add("?"); argumentVal.add(PropertyUtils.getProperty(instance, field.getName()).toString()); argumentType.add(PropertyUtils.getPropertyType(instance, field.getName()).toString()); } }else { argumentName.add(field.getName()); placeHolder.add("?"); argumentVal.add(PropertyUtils.getProperty(instance, field.getName()).toString()); argumentType.add(PropertyUtils.getPropertyType(instance, field.getName()).toString()); } } @SuppressWarnings("unchecked") final String sql = "insert into "+getTableName(c)+" ("+StringUtils.join(argumentName.toArray(), ',')+") values ("+StringUtils.join(placeHolder.toArray(), ',')+")"; System.out.println("SQL: "+sql); KeyHolder holder=new GeneratedKeyHolder(); final LinkedList<String> passedVal=argumentVal; final LinkedList<String> passedType=argumentType; jdbcTemplate.update(new PreparedStatementCreator() { @SuppressWarnings("deprecation") @Override public PreparedStatement createPreparedStatement(Connection cn) throws SQLException { PreparedStatement preparedStatement = cn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); int col=1; for(int i=0;i<passedVal.size();i++){ String type=passedType.get(i); switch(type){ case "class java.lang.String": preparedStatement.setString(col, passedVal.get(i)); col++; break; case "int": preparedStatement.setInt(col, Integer.parseInt(passedVal.get(i))); col++; break; case "class java.util.Date": //preparedStatement.setObject(col, passedVal.get(i)); preparedStatement.setDate(col, new java.sql.Date(new java.util.Date(passedVal.get(i)).getTime())); col++; break; default: System.out.println(type+" Not found"); } } return preparedStatement; } },holder); return holder.getKey().intValue(); }catch(Exception e){e.printStackTrace();return 0;} } public int updateRecord(T instance) { try{ @SuppressWarnings("rawtypes") Class c=Class.forName(instance.getClass().getName()); LinkedList<String> argumentName=new LinkedList<String>(); LinkedList<String> argumentVal=new LinkedList<String>(); LinkedList<String> argumentType=new LinkedList<String>(); Field[] fields=instance.getClass().getDeclaredFields(); for(Field field:fields){ if(field.getAnnotation(Column.class)!=null){ if(field.getAnnotation(Column.class).unique()==true){ } else if (field.getAnnotation(Column.class).insertable()==false){ } else if (field.getAnnotation(Column.class).name().length()>0){ argumentName.add(field.getAnnotation(Column.class).name()+" = ?"); argumentVal.add(PropertyUtils.getProperty(instance, field.getName()).toString()); argumentType.add(PropertyUtils.getPropertyType(instance, field.getName()).toString()); } else { } } else { argumentName.add(field.getName()+" = ?"); argumentVal.add(PropertyUtils.getProperty(instance, field.getName()).toString()); argumentType.add(PropertyUtils.getPropertyType(instance, field.getName()).toString()); } } @SuppressWarnings("unchecked") final String sql ="update "+getTableName(c)+" set "+StringUtils.join(argumentName.toArray()," , ")+" where "+getUniqueColumnAnnotation(c)+" = ?"; @SuppressWarnings("unchecked") String key=PropertyUtils.getProperty(instance, getUniqueColumnName(c)).toString(); @SuppressWarnings("unchecked") String keyType=PropertyUtils.getPropertyType(instance, getUniqueColumnName(c)).toString(); argumentVal.add(key); argumentType.add(keyType); final LinkedList<String> passedVal=argumentVal; final LinkedList<String> passedType=argumentType; return jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection cn) throws SQLException { PreparedStatement preparedStatement = cn.prepareStatement(sql); int col=1; for(int i=0;i<passedVal.size();i++){ String type=passedType.get(i); //System.out.println("-----"+passedVal.get(i)+": "+passedType.get(i)); switch(type){ case "class java.lang.String": preparedStatement.setObject(col, passedVal.get(i)); col++; break; case "int": preparedStatement.setInt(col, Integer.parseInt(passedVal.get(i))); col++; break; case "class java.util.Date": preparedStatement.setObject(col, passedVal.get(i)); col++; break; default: System.out.println(type+" Not found"); } } return preparedStatement; } }); }catch(Exception e){e.printStackTrace();return 0;} } private String getTableName(Class<T> clazz) { Entity entityAnnotation = clazz.getAnnotation(Entity.class); if (entityAnnotation != null && org.springframework.util.StringUtils.hasText(entityAnnotation.name())) return entityAnnotation.name(); return clazz.getSimpleName(); } private String getActualColumName(Class<T> clazz, String columnName) { Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ if(field.getAnnotation(Column.class)!=null){ if(field.getAnnotation(Column.class).name().equals(columnName)){ return field.getName(); } } } return columnName; } private String getUniqueColumnAnnotation(Class<T> clazz) { Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ if(field.getAnnotation(Column.class)!=null){ if(field.getAnnotation(Column.class).unique()==true){ return field.getAnnotation(Column.class).name(); } } } return null; } private String getUniqueColumnName(Class<T> clazz) { Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ if(field.getAnnotation(Column.class)!=null){ if(field.getAnnotation(Column.class).unique()==true){ return field.getName(); } } } return null; } @Override public T findById(Class<T> entityClass, int id) { return (T) jdbcTemplate.queryForObject("select * from "+getTableName(entityClass)+" where "+getUniqueColumnAnnotation(entityClass)+" = "+id, new EntityRowMapper<>(entityClass)); } @Override public void update(T instance) { System.out.println(updateRecord(instance)); } @Override public int delete(Class<T> entityClass, int id) { return jdbcTemplate.update("delete from "+getTableName(entityClass)+" where id="+id); } @Override public int deleteAll(Class<T> entityClass) { return jdbcTemplate.update("delete from "+getTableName(entityClass)); } @Override public void save(T instance) { System.out.println(insertRecord(instance)); } @Override public List<T> getList(Class<T> entity) { return jdbcTemplate.query("select * from "+getTableName(entity), new EntityRowMapper<>(entity)); } @Override public List<String> getMetadata(Class<T> entity) { return jdbcTemplate.queryForList("select column_name from user_tab_columns where table_name='"+getTableName(entity)+"'",String.class); } @Override public List<String> getColumnHeader(Class<T> entity) { List<String> arrayList=new ArrayList<String>(); Field[] fields=entity.getDeclaredFields(); for(Field f:fields){ arrayList.add(f.getName()); } return arrayList; } @Override public List<T> getListCustom(Class<T> entity, String customQuery) { return jdbcTemplate.query("select * from "+getTableName(entity)+" where " + customQuery, new EntityRowMapper<>(entity)); } @Override public List<T> findByProperty(Class<T> entity, String paramName, Object value) { return jdbcTemplate.query("select * from "+getTableName(entity)+" where " + getActualColumName(entity,paramName)+" = "+value, new EntityRowMapper<>(entity)); } }
Java
package insight.sm.dao; import insight.sm.pojo.MCRDetail; public class MCRDetailDAOImpl extends GenericDAOImpl<MCRDetail> implements IMCRDetailDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.ReceiptDetails; public class ReceiptDetailsDAOImpl extends GenericDAOImpl<ReceiptDetails> implements IReceiptDetailsDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.Assignments; public class AssignmentsDAOImpl extends GenericDAOImpl<Assignments> implements IAssignmentsDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.Equipment; public interface IEquipmentDAO extends IGenericDAO<Equipment> { }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialRequirement; public class MaterialRequirementDAOImpl extends GenericDAOImpl<MaterialRequirement> implements IMaterialRequirementDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialReceipts; public class MaterialReceiptsDAOImpl extends GenericDAOImpl<MaterialReceipts> implements IMaterialReceiptsDAO{ }
Java
package insight.sm.dao; import java.util.List; public interface IGenericDAO<T> { public T findById(Class<T> T, int id); public void update(T object); public int delete(Class<T> T,int id); public int deleteAll(Class<T> T); public void save(T instance); public List<T> getList(Class<T> entity); public List<String> getMetadata(Class<T> entity); public List<String> getColumnHeader(Class<T> entity); public List<T> getListCustom(Class<T> entity,String customQuery); List<T> findByProperty(Class<T> entity, String paramName, Object value); }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialIssue; public class MaterialIssueDAOImpl extends GenericDAOImpl<MaterialIssue> implements IMaterialIssueDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.Assignments; public interface IAssignmentsDAO extends IGenericDAO<Assignments> { }
Java
package insight.sm.dao; import insight.sm.pojo.MCRMaster; public interface IMCRMasterDAO extends IGenericDAO<MCRMaster> { }
Java
package insight.sm.dao; import insight.sm.pojo.MCRDetail; public interface IMCRDetailDAO extends IGenericDAO<MCRDetail> { }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialReceipts; public interface IMaterialReceiptsDAO extends IGenericDAO<MaterialReceipts> { }
Java
package insight.sm.dao; import insight.sm.pojo.Task; public interface ITaskDAO extends IGenericDAO<Task>{ }
Java
package insight.sm.dao; import insight.sm.pojo.Project; public class ProjectDAOImpl extends GenericDAOImpl<Project> implements IProjectDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.Material; public class MaterialDAOImpl extends GenericDAOImpl<Material> implements IMaterialDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.Project; public interface IProjectDAO extends IGenericDAO<Project> { }
Java
package insight.sm.dao; import insight.sm.pojo.MaterialRequirement; public interface IMaterialRequirementDAO extends IGenericDAO<MaterialRequirement> { }
Java
package insight.sm.dao; import insight.sm.pojo.Equipment; public class EquipmentDAOImpl extends GenericDAOImpl<Equipment> implements IEquipmentDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.MCRMaster; public class MCRMasterDAOImpl extends GenericDAOImpl<MCRMaster> implements IMCRMasterDAO{ }
Java
package insight.sm.dao; import insight.sm.pojo.ReceiptDetails; public interface IReceiptDetailsDAO extends IGenericDAO<ReceiptDetails>{ }
Java
package insight.sm.dao; import insight.sm.pojo.Material; public interface IMaterialDAO extends IGenericDAO<Material> { }
Java
package insight.sm.dao; import insight.sm.pojo.LabourResources; public interface ILabourResourcesDAO extends IGenericDAO<LabourResources> { }
Java
package insight.sm.dao; import insight.sm.pojo.LabourResources; public class LabourResourcesDAOImpl extends GenericDAOImpl<LabourResources> implements ILabourResourcesDAO{ }
Java
package insight.sm.delegates; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; public class ReflectionDelegate { public static <T extends Annotation> Field[] getAnnotatedFields( Class<?> clazz, Class<T> annotClass) { ArrayList<Field> fields = new ArrayList<Field>(); for (Field field : clazz.getDeclaredFields()) { if (field.getAnnotation(annotClass) != null) { fields.add(field); } } return fields.toArray(new Field[fields.size()]); } public static Method getSetterMethod(Field field) { Method[] methods = field.getDeclaringClass().getMethods(); System.out.println("Found " + methods.length + " method(s)."); for (Method method : methods) { System.out.println("Checking method " + method.getName()); if (Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(field.getType()) && method.getName().equalsIgnoreCase("set" + field.getName())) { return method; } } return null; } }
Java
package insight.sm.delegates; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONStringer; /** * * AjaxJSONDelegate class set json object in HttpServletResponse and send back * to the UI. * */ public class AjaxDelegate { /** * * @param jarray * holds the response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONArray jarray, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jarray.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param content * holds the response values * @param res * is HttpServletResonse. */ public static void setTextResponse(final String content, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(content); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * * @param jsonStringer * holds response values * @param res * is HttpServletResonse. */ public static void setResponse(final JSONStringer jsonStringer, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); w.write(jsonStringer.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void setResponse(final JSONObject obj, final HttpServletResponse res) { try { Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8"); // System.out.print(obj.toString()); w.write(obj.toString()); w.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void setResponse(InputStream inStream, HttpServletResponse response, String type) throws IOException { if (type != null) response.setContentType(type); IOUtils.copy(inStream, response.getOutputStream()); } }
Java
package insight.sm.controllers; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.json.JSONException; import org.json.JSONObject; public class GenericController { public static JSONObject readJSON(HttpServletRequest request) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = request.getReader(); String str; while ((str = br.readLine()) != null) { sb.append(str); } try { JSONObject jObj = new JSONObject(sb.toString()); return jObj; } catch (JSONException e) { e.printStackTrace(); return null; } } }
Java
package insight.sm.controllers; import insight.sm.delegates.AjaxDelegate; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController extends GenericController { @RequestMapping("/home.htm") public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView(); mav.addObject("serverTime", "10:00pm"); return mav; } @RequestMapping("/grid.htm") public ModelAndView grid(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView(); mav.addObject("serverTime", "10:00pm"); return new ModelAndView(); } @RequestMapping("/project.htm") public ModelAndView project(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("project"); mav.addObject("serverTime", "10:00pm"); return new ModelAndView(); } @RequestMapping("/users.htm") public ModelAndView listUsers(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView(); mav.addObject("serverTime", "10:00pm"); return new ModelAndView(); } @RequestMapping("/home1.htm") public ModelAndView home1(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav=new ModelAndView("home1"); mav.addObject("serverTime", "10:00pm"); return mav; } @RequestMapping("loadUsrAvatar.htm") public ModelAndView loadUserAvatar(HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream readImg = new FileInputStream( "F:/Workspaces/Spring4/SiteMan/WebContent/resources/app/images/avatar1.jpg"); AjaxDelegate.setResponse(readImg, response, "image/jpg"); return null; } @RequestMapping("getList.htm") public ModelAndView getList(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) throws IOException, JSONException { JSONArray jAry = new JSONArray(); jAry.put(new JSONObject().put("value", "1").put("text", "One")); AjaxDelegate.setResponse(jAry, response); return null; } @RequestMapping("loadBookmarks.htm") public ModelAndView loadBookmarks(HttpServletRequest request, HttpServletResponse response, @RequestParam("topOnly") boolean topOnly) throws IOException, JSONException { JSONArray jAry = new JSONArray(); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket") .put("title", "SB-1000, Right to Way not available in Zone 2") .put("text", "QI-01811, Right to way...")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket") .put("title", "SB-1000, Right to Way not available in Zone 2") .put("text", "QI-01811, Right to way...")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket") .put("title", "SB-1000, Right to Way not available in Zone 2") .put("text", "QI-01811, Right to way...")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket") .put("title", "SB-1000, Right to Way not available in Zone 2") .put("text", "QI-01811, Right to way...")); AjaxDelegate.setResponse(jAry, response); return null; } @RequestMapping("loadReports.htm") public ModelAndView loadReports(HttpServletRequest request, HttpServletResponse response, @RequestParam("topOnly") boolean topOnly) throws IOException, JSONException { JSONArray jAry = new JSONArray(); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket").put("title", "Report1") .put("text", "Report1")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket").put("title", "Report 2") .put("text", "Report 2")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket").put("title", "Report 3") .put("text", "Report 3")); jAry.put(new JSONObject().put("type", "1").put("id", 2) .put("iconClass", "fa-ticket").put("title", "Report 4") .put("text", "Report 4")); AjaxDelegate.setResponse(jAry, response); return null; } @RequestMapping("loadProjectNavigator.htm") public ModelAndView loadProjectNavigator(HttpServletRequest request, HttpServletResponse response, @RequestParam("topOnly") boolean topOnly) throws IOException, JSONException { JSONArray jAry = new JSONArray(); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Create New") .put("text", "Create New")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Tasks") .put("text", "Tasks")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Pictures") .put("text", "Pictures")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Messages") .put("text", "Messages")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Transmittals") .put("text", "Transmittals")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Submittals") .put("text", "Submittals")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Issues") .put("text", "Issues")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Risks") .put("text", "Risks")); jAry.put(new JSONObject().put("type", "1") .put("iconClass", "fa-ticket").put("title", "Safety Incidents") .put("text", "Safety Incidents")); AjaxDelegate.setResponse(jAry, response); return null; } @RequestMapping("loadBullitenBoard.htm") public ModelAndView loadBullitenBoard(HttpServletRequest request, HttpServletResponse response, @RequestParam("topOnly") boolean topOnly) throws IOException, JSONException { JSONArray jAry = new JSONArray(); jAry.put(new JSONObject() .put("type", "1") .put("id", 2) .put("avatarClass", "avatar blue") .put("iconClass", "fa fa-rss fa-2x") .put("date", "06-Jan") .put("title", "Twitter Bootstrap v3.0 is coming!") .put("text", "With 2.2.2 out the door, our attention has shifted almost entirely to the next major update to the project ...")); jAry.put(new JSONObject() .put("type", "1") .put("id", 2) .put("avatarClass", "avatar green") .put("iconClass", "fa fa-comment-o fa-2x") .put("date", "11-Feb") .put("title", "Ruby on Rails 4.0") .put("text", "Rails 4.0 is still unfinished, but it is shaping up to become a great release ...")); jAry.put(new JSONObject() .put("type", "1") .put("id", 2) .put("avatarClass", "avatar purple") .put("date", "04-Mar") .put("iconClass", "fa fa-calendar-o fa-2x") .put("title", "All about SCSS") .put("text", "Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules ...")); AjaxDelegate.setResponse(jAry, response); return null; } }
Java