code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * 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(); } }
11durong-mytest1
google-api-client/src/com/google/api/client/json/GenericJson.java
Java
asf20
1,369
/* * 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); } } }
11durong-mytest1
google-api-client/src/com/google/api/client/json/Json.java
Java
asf20
18,534
/* * 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; } }
11durong-mytest1
google-api-client/src/com/google/api/client/json/CustomizeJsonParser.java
Java
asf20
1,828
<body> JSON-RPC 2.0 as specified in <a href="http://groups.google.com/group/json-rpc/web/json-rpc-2-0">JSON-RPC 2.0 Specification</a> and <a href="http://groups.google.com/group/json-rpc/web/json-rpc-over-http">JSON-RPC over HTTP</a> . <p>This package depends on theses packages:</p> <ul> <li>{@link com.google.api.client.http}</li> <li>{@link com.google.api.client.json}</li> <li>{@link com.google.api.client.util}</li> </ul> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/json/rpc2/package.html
HTML
asf20
623
/* * 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; } }
11durong-mytest1
google-api-client/src/com/google/api/client/json/rpc2/JsonRpcHttpTransport.java
Java
asf20
5,191
/* * 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; }
11durong-mytest1
google-api-client/src/com/google/api/client/json/rpc2/JsonRpcRequest.java
Java
asf20
1,497
<body> HTTP Transport library for Google API's based on Apache HTTP Client version 4. <p>This package depends on theses packages:</p> <ul> <li>{@link com.google.api.client.http}</li> <li>{@code org.apache.http.*}</li> </ul> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/apache/package.html
HTML
asf20
419
/* * 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; } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/PlainSocksSocketFactory.java
Java
asf20
4,345
/* * 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); } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/ContentEntity.java
Java
asf20
1,466
/* * 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); } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/ApacheHttpRequest.java
Java
asf20
1,847
/* * 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(); } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/ApacheHttpResponse.java
Java
asf20
2,981
/* * 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"; } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/HttpPatch.java
Java
asf20
921
/* * 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(); } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/TrustManagerDecorator.java
Java
asf20
1,771
/* * 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; } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/SSLSocksSocketFactory.java
Java
asf20
9,104
/* * 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"); } }
11durong-mytest1
google-api-client/src/com/google/api/client/apache/ApacheHttpTransport.java
Java
asf20
5,756
/* * 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); } }
11durong-mytest1
google-api-client/src/com/google/api/client/repackaged/com/google/common/base/Objects.java
Java
asf20
1,457
<body> Copied from <a href="http://code.google.com/p/guava-libraries">guava-libraries</a> , but only keeping the stuff we actually need. <p>Rather than having an explicit dependency on guava-libraries, we repackage just the few classes we need from guava-libraries to better support low-space environments like Android. Note that some functionality may be removed from some of the classes to minimize size, so it is not necessarily an exact copy.</p> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/repackaged/com/google/common/base/package.html
HTML
asf20
641
/* * 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(); } }
11durong-mytest1
google-api-client/src/com/google/api/client/repackaged/com/google/common/base/Preconditions.java
Java
asf20
17,234
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* * This is the Cisco Netflow(tm) version 5 packet format * Based on: * http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm */ struct NF5_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec, time_nanosec, flow_sequence; u_int8_t engine_type, engine_id, reserved1, reserved2; }; struct NF5_FLOW { u_int32_t src_ip, dest_ip, nexthop_ip; u_int16_t if_index_in, if_index_out; u_int32_t flow_packets, flow_octets; u_int32_t flow_start, flow_finish; u_int16_t src_port, dest_port; u_int8_t pad1; u_int8_t tcp_flags, protocol, tos; u_int16_t src_as, dest_as; u_int8_t src_mask, dst_mask; u_int16_t pad2; }; #define NF5_MAXFLOWS 30 #define NF5_MAXPACKET_SIZE (sizeof(struct NF5_HEADER) + \ (NF5_MAXFLOWS * sizeof(struct NF5_FLOW))) /* * Given an array of expired flows, send netflow v5 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v5(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct timeval now; u_int32_t uptime_ms; u_int8_t packet[NF5_MAXPACKET_SIZE]; /* Maximum allowed packet size (24 flows) */ struct NF5_HEADER *hdr = NULL; struct NF5_FLOW *flw = NULL; int i, j, offset, num_packets, err; socklen_t errsz; gettimeofday(&now, NULL); uptime_ms = timeval_sub_ms(&now, system_boot_time); hdr = (struct NF5_HEADER *)packet; for (num_packets = offset = j = i = 0; i < num_flows; i++) { if (j >= NF5_MAXFLOWS - 1) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); *flows_exported += j; j = 0; num_packets++; } if (j == 0) { memset(&packet, '\0', sizeof(packet)); hdr->version = htons(5); hdr->flows = 0; /* Filled in as we go */ hdr->uptime_ms = htonl(uptime_ms); hdr->time_sec = htonl(now.tv_sec); hdr->time_nanosec = htonl(now.tv_usec * 1000); hdr->flow_sequence = htonl(*flows_exported); /* Other fields are left zero */ offset = sizeof(*hdr); } flw = (struct NF5_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); /* NetFlow v.5 doesn't do IPv6 */ if (flows[i]->af != AF_INET) continue; if (flows[i]->octets[0] > 0) { flw->src_ip = flows[i]->addr[0].v4.s_addr; flw->dest_ip = flows[i]->addr[1].v4.s_addr; flw->src_port = flows[i]->port[0]; flw->dest_port = flows[i]->port[1]; flw->flow_packets = htonl(flows[i]->packets[0]); flw->flow_octets = htonl(flows[i]->octets[0]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->tcp_flags = flows[i]->tcp_flags[0]; flw->protocol = flows[i]->protocol; offset += sizeof(*flw); j++; hdr->flows++; } flw = (struct NF5_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); if (flows[i]->octets[1] > 0) { flw->src_ip = flows[i]->addr[1].v4.s_addr; flw->dest_ip = flows[i]->addr[0].v4.s_addr; flw->src_port = flows[i]->port[1]; flw->dest_port = flows[i]->port[0]; flw->flow_packets = htonl(flows[i]->packets[1]); flw->flow_octets = htonl(flows[i]->octets[1]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->tcp_flags = flows[i]->tcp_flags[1]; flw->protocol = flows[i]->protocol; offset += sizeof(*flw); j++; hdr->flows++; } } /* Send any leftovers */ if (j != 0) { if (verbose_flag) logit(LOG_DEBUG, "Sending v5 flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; } *flows_exported += j; return (num_packets); }
08beeumerk-flow
netflow5.c
C
bsd
5,710
/* * Copyright (c) 2007 Damien Miller. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" #include "freelist.h" #include "log.h" #define FREELIST_MAX_ALLOC 0x1000000 #define FREELIST_ALLOC_ALIGN 16 #define FREELIST_INITIAL_ALLOC 16 #ifndef roundup #define roundup(x, y) ((((x) + (y) - 1)/(y))*(y)) #endif /* roundup */ #undef FREELIST_DEBUG #ifdef FREELIST_DEBUG # define FLOGIT(a) logit a #else # define FLOGIT(a) #endif void freelist_init(struct freelist *fl, size_t allocsz) { FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, allocsz)); bzero(fl, sizeof(fl)); fl->allocsz = roundup(allocsz, FREELIST_ALLOC_ALIGN); fl->free_entries = NULL; } static int freelist_grow(struct freelist *fl) { size_t i, oldnalloc, need; void *p; FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl)); FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->nalloc)); /* Sanity check */ if (fl->nalloc > FREELIST_MAX_ALLOC) return -1; oldnalloc = fl->nalloc; if (fl->nalloc == 0) fl->nalloc = FREELIST_INITIAL_ALLOC; else fl->nalloc <<= 1; if (fl->nalloc > FREELIST_MAX_ALLOC) fl->nalloc = FREELIST_MAX_ALLOC; FLOGIT((LOG_DEBUG, "%s: nalloc now %zu", __func__, fl->nalloc)); /* Check for integer overflow */ if (SIZE_MAX / fl->nalloc < fl->allocsz || SIZE_MAX / fl->nalloc < sizeof(*fl->free_entries)) { FLOGIT((LOG_DEBUG, "%s: integer overflow", __func__)); resize_fail: fl->nalloc = oldnalloc; return -1; } /* Allocate freelist - max size of nalloc */ need = fl->nalloc * sizeof(*fl->free_entries); if ((p = realloc(fl->free_entries, need)) == NULL) { FLOGIT((LOG_DEBUG, "%s: realloc(%zu) failed", __func__, need)); goto resize_fail; } /* Allocate the entries */ fl->free_entries = p; need = (fl->nalloc - oldnalloc) * fl->allocsz; if ((p = malloc(need)) == NULL) { FLOGIT((LOG_DEBUG, "%s: malloc(%zu) failed", __func__, need)); goto resize_fail; } /* * XXX store these malloc ranges in a tree or list, so we can * validate them in _get/_put. Check that r_low <= addr < r_high, and * (addr - r_low) % fl->allocsz == 0 */ fl->navail = fl->nalloc - oldnalloc; for (i = 0; i < fl->navail; i++) fl->free_entries[i] = (u_char *)p + (i * fl->allocsz); for (i = fl->navail; i < fl->nalloc; i++) fl->free_entries[i] = NULL; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); return 0; } void * freelist_get(struct freelist *fl) { void *r; FLOGIT((LOG_DEBUG, "%s: %s(%p)", __func__, __func__, fl)); FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail)); if (fl->navail == 0) { if (freelist_grow(fl) == -1) return NULL; } /* Sanity check */ if (fl->navail == 0 || fl->navail > FREELIST_MAX_ALLOC || fl->free_entries[fl->navail - 1] == NULL) { logit(LOG_ERR, "%s: invalid navail", __func__); raise(SIGSEGV); } fl->navail--; r = fl->free_entries[fl->navail]; fl->free_entries[fl->navail] = NULL; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); return r; } void freelist_put(struct freelist *fl, void *p) { FLOGIT((LOG_DEBUG, "%s: %s(%p, %zu)", __func__, __func__, fl, p)); FLOGIT((LOG_DEBUG, "%s: navail = %zu", __func__, fl->navail)); FLOGIT((LOG_DEBUG, "%s: nalloc = %zu", __func__, fl->navail)); /* Sanity check */ if (fl->navail >= fl->nalloc) { logit(LOG_ERR, "%s: freelist navail >= nalloc", __func__); raise(SIGSEGV); } if (fl->free_entries[fl->navail] != NULL) { logit(LOG_ERR, "%s: free_entries[%lu] != NULL", __func__, (unsigned long)fl->navail); raise(SIGSEGV); } fl->free_entries[fl->navail] = p; fl->navail++; FLOGIT((LOG_DEBUG, "%s: done, navail = %zu", __func__, fl->navail)); }
08beeumerk-flow
freelist.c
C
bsd
4,923
# $Id$ # # Copyright (c) 2004 Damien Miller # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_INIT AC_CONFIG_SRCDIR([softflowd.c]) AC_CONFIG_HEADER(config.h) AC_PROG_CC AC_PROG_INSTALL # Optional verbose warnings for gcc, see below WFLAGS="-Wall -Waggregate-return -Wcast-align -Wcast-qual" WFLAGS="$WFLAGS -Wmissing-declarations -Wmissing-prototypes" WFLAGS="$WFLAGS -Wno-conversion -Wpointer-arith -Wshadow" WFLAGS="$WFLAGS -Wuninitialized -Wcast-align -Wcast-qual" WFLAGS="$WFLAGS -Wformat=2 -Wformat-nonliteral -Wwrite-strings" # Process flag arguments early, so they are available for tests later AC_ARG_ENABLE(gcc-warnings, [ --enable-gcc-warnings Enable verbose warnings (only for gcc)], [ if test "x$enableval" = "xyes" ; then CFLAGS="$CFLAGS $WFLAGS"; fi ] ) AC_ARG_WITH(cflags, [ --with-cflags Specify additional compiler flags], [ if test "x$withval" != "xno" ; then CFLAGS="$CFLAGS $withval"; fi ] ) AC_ARG_WITH(cppflags, [ --with-cppflags Specify additional preprocessor flags] , [ if test "x$withval" != "xno"; then CPPFLAGS="$CPPFLAGS $withval"; fi ] ) AC_ARG_WITH(ldflags, [ --with-ldflags Specify additional linker flags], [ if test "x$withval" != "xno" ; then LDFLAGS="$LDFLAGS $withval"; fi ] ) AC_ARG_WITH(libs, [ --with-libs Specify additional libraries to link with], [ if test "x$withval" != "xno" ; then LIBS="$LIBS $withval"; fi ] ) AC_CHECK_HEADERS(net/bpf.h pcap.h pcap-bpf.h) dnl AC_CHECK_HEADERS(netinet/in_systm.h netinet/tcp.h netinet/udp.h) dnl dnl # This ugliness is because of autoconf's stupid default include list dnl AC_CHECK_HEADERS([netinet/ip.h], dnl [AC_DEFINE([HAVE_HAVE_NETINET_IP_H], 1, [has netinet/ip.h])], [], dnl [ dnl #include <sys/types.h> dnl #include <netinet/in.h> dnl #if HAVE_NETINET_IN_SYSTM_H dnl #include <netinet/in_systm.h> dnl #endif dnl ]) AC_CHECK_MEMBER([struct sockaddr.sa_len], [AC_DEFINE([SOCK_HAS_LEN], 1, [struct sockaddr contains length])], , [#include <sys/types.h> #include <sys/socket.h>]) AC_CHECK_MEMBER(struct ip6_ext.ip6e_nxt, [AC_DEFINE([HAVE_STRUCT_IP6_EXT], 1, [struct ip6_ext.ip6e_nxt exists])], [], [ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip6.h> ]) AC_SEARCH_LIBS(daemon, bsd) AC_SEARCH_LIBS(gethostbyname, nsl) AC_SEARCH_LIBS(socket, socket) AC_CHECK_LIB(pcap, pcap_open_live) AC_CHECK_FUNCS(closefrom daemon setresuid setreuid setresgid setgid strlcpy strlcat) AC_CHECK_TYPES([u_int64_t, int64_t, uint64_t, u_int32_t, int32_t, uint32_t]) AC_CHECK_TYPES([u_int16_t, int16_t, uint16_t, u_int8_t, int8_t, uint8_t]) AC_CHECK_SIZEOF(char, 1) AC_CHECK_SIZEOF(short int, 2) AC_CHECK_SIZEOF(int, 4) AC_CHECK_SIZEOF(long int, 4) AC_CHECK_SIZEOF(long long int, 8) if test "x$ac_cv_type_uint8_t" = "xyes" ; then AC_DEFINE([OUR_CFG_U_INT8_T], [uint8_t], [8-bit unsigned int]) elif test "x$ac_cv_sizeof_char" = "x1" ; then AC_DEFINE([OUR_CFG_U_INT8_T], [unsigned char], [8-bit unsigned int]) else AC_MSG_ERROR([No 8-bit unsigned int type found]) fi if test "x$ac_cv_sizeof_char" = "x1" ; then AC_DEFINE([OUR_CFG_INT8_T], [signed char], [8-bit signed int]) else AC_MSG_ERROR([No 8-bit signed int type found]) fi if test "x$ac_cv_type_uint16_t" = "xyes" ; then AC_DEFINE([OUR_CFG_U_INT16_T], [uint16_t], [16-bit unsigned int]) elif test "x$ac_cv_sizeof_short_int" = "x2" ; then AC_DEFINE([OUR_CFG_U_INT16_T], [unsigned short int], [16-bit unsigned int]) else AC_MSG_ERROR([No 16-bit unsigned int type found]) fi if test "x$ac_cv_sizeof_short_int" = "x2" ; then AC_DEFINE([OUR_CFG_INT16_T], [short int], [16-bit signed int]) else AC_MSG_ERROR([No 16-bit signed int type found]) fi if test "x$ac_cv_type_uint32_t" = "xyes" ; then AC_DEFINE([OUR_CFG_U_INT32_T], [uint32_t], [32-bit unsigned int]) elif test "x$ac_cv_sizeof_int" = "x4" ; then AC_DEFINE([OUR_CFG_U_INT32_T], [unsigned int], [32-bit unsigned int]) else AC_MSG_ERROR([No 32-bit unsigned int type found]) fi if test "x$ac_cv_sizeof_int" = "x4" ; then AC_DEFINE([OUR_CFG_INT32_T], [int], [32-bit signed int]) else AC_MSG_ERROR([No 32-bit signed int type found]) fi if test "x$ac_cv_type_uint64_t" = "xyes" ; then AC_DEFINE([OUR_CFG_U_INT64_T], [uint64_t], [64-bit unsigned int]) elif test "x$ac_cv_sizeof_long_int" = "x8" ; then AC_DEFINE([OUR_CFG_U_INT64_T], [unsigned long int], [64-bit unsigned int]) elif test "x$ac_cv_sizeof_long_long_int" = "x8" ; then AC_DEFINE([OUR_CFG_U_INT64_T], [unsigned long long int], [64-bit unsigned int]) else AC_MSG_ERROR([No 64-bit unsigned int type found]) fi if test "x$ac_cv_sizeof_long_int" = "x8" ; then AC_DEFINE([OUR_CFG_INT64_T], [long int], [64-bit signed int]) elif test "x$ac_cv_sizeof_long_long_int" = "x8" ; then AC_DEFINE([OUR_CFG_INT64_T], [long long int], [64-bit signed int]) else AC_MSG_ERROR([No 64-bit signed int type found]) fi if test "x$ac_cv_header_pcap_bpf_h" != "xyes" && \ test "x$ac_cv_header_net_bpf_h" != "xyes" ; then AC_MSG_ERROR([No BPF header found]) fi if test "x$ac_cv_header_pcap_h" != "xyes" ; then AC_MSG_ERROR([No pcap.h header found]) fi if test "x$ac_cv_lib_pcap_pcap_open_live" != "xyes" ; then AC_MSG_ERROR([libpcap not found]) fi AC_EXEEXT AC_CONFIG_FILES([Makefile]) AC_OUTPUT
08beeumerk-flow
configure.ac
M4Sugar
bsd
5,938
.\" $Id$ .\" .\" Copyright (c) 2002 Damien Miller. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. .\" .Dd October 18, 2002 .Dt SOFTFLOWCTL 8 .Os .Sh NAME .Nm softflowctl .Nd Remote control program for softflowd .Sh SYNOPSIS .Nm softflowctl .Op Fl h .Op Fl c Ar ctl_sock .Ar command .Sh DESCRIPTION .Nm is a remote control program used to control a running .Xr softflowd 8 daemon. .Pp The command line options are as follows: .Bl -tag -width Ds .It Fl c Ar ctlsock Specify an alternate location for the remote control socket. Default is .Pa /var/run/softflowd.ctl .It Fl h Display command line usage information. .El .Pp .Sh COMMANDS .Bl -tag -width Ds .It Pa shutdown Ask .Xr softflowd 8 to gracefully exit. This is equivalent to sending it a .Dv SIGTERM or .Dv SIGINT . .It Pa exit Ask .Xr softflowd 8 to immediately exit. No flow expiry processing or data export is performed. .It Pa expire-all Immediately expire all tracked flows. .It Pa delete-all Immediately delete all tracked flows. No flow expiry processing or data export is performed. .It Pa statistics Return statistics collected by .Xr softflowd 8 on expired flows. .It Pa debug+ Increase the debugging level of .Xr softflowd 8 .It Pa debug- Decrease the debugging level. .It Pa stop-gather Stops network data collection by .Xr softflowd 8 . .It Pa start-gather Resumes network data collection. .It Pa dump-flows Return information on all tracked flows. .It Pa timeouts Print information on flow timeout parameters. .It Pa send-template Resend a NetFlow v.9 template record before the next flow export. Has no effect for other flow export versions. .El .Sh BUGS All times are unconditionally displayed in UTC, regardless of the system timezone. .Sh AUTHORS .An Damien Miller Aq djm@mindrot.org .Sh SEE ALSO .Xr softflowd 8
08beeumerk-flow
softflowctl.8
Roff Manpage
bsd
3,031
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* * This is the Cisco Netflow(tm) version 1 packet format * Based on: * http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm */ struct NF1_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec, time_nanosec; }; struct NF1_FLOW { u_int32_t src_ip, dest_ip, nexthop_ip; u_int16_t if_index_in, if_index_out; u_int32_t flow_packets, flow_octets; u_int32_t flow_start, flow_finish; u_int16_t src_port, dest_port; u_int16_t pad1; u_int8_t protocol, tos, tcp_flags; u_int8_t pad2, pad3, pad4; u_int32_t reserved1; #if 0 u_int8_t reserved2; /* XXX: no longer used */ #endif }; /* Maximum of 24 flows per packet */ #define NF1_MAXFLOWS 24 #define NF1_MAXPACKET_SIZE (sizeof(struct NF1_HEADER) + \ (NF1_MAXFLOWS * sizeof(struct NF1_FLOW))) /* * Given an array of expired flows, send netflow v1 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v1(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct timeval now; u_int32_t uptime_ms; u_int8_t packet[NF1_MAXPACKET_SIZE]; /* Maximum allowed packet size (24 flows) */ struct NF1_HEADER *hdr = NULL; struct NF1_FLOW *flw = NULL; int i, j, offset, num_packets, err; socklen_t errsz; gettimeofday(&now, NULL); uptime_ms = timeval_sub_ms(&now, system_boot_time); hdr = (struct NF1_HEADER *)packet; for(num_packets = offset = j = i = 0; i < num_flows; i++) { if (j >= NF1_MAXFLOWS - 1) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); *flows_exported += j; j = 0; num_packets++; } if (j == 0) { memset(&packet, '\0', sizeof(packet)); hdr->version = htons(1); hdr->flows = 0; /* Filled in as we go */ hdr->uptime_ms = htonl(uptime_ms); hdr->time_sec = htonl(now.tv_sec); hdr->time_nanosec = htonl(now.tv_usec * 1000); offset = sizeof(*hdr); } flw = (struct NF1_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); /* NetFlow v.1 doesn't do IPv6 */ if (flows[i]->af != AF_INET) continue; if (flows[i]->octets[0] > 0) { flw->src_ip = flows[i]->addr[0].v4.s_addr; flw->dest_ip = flows[i]->addr[1].v4.s_addr; flw->src_port = flows[i]->port[0]; flw->dest_port = flows[i]->port[1]; flw->flow_packets = htonl(flows[i]->packets[0]); flw->flow_octets = htonl(flows[i]->octets[0]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->protocol = flows[i]->protocol; flw->tcp_flags = flows[i]->tcp_flags[0]; offset += sizeof(*flw); j++; hdr->flows++; } flw = (struct NF1_FLOW *)(packet + offset); flw->if_index_in = flw->if_index_out = htons(ifidx); if (flows[i]->octets[1] > 0) { flw->src_ip = flows[i]->addr[1].v4.s_addr; flw->dest_ip = flows[i]->addr[0].v4.s_addr; flw->src_port = flows[i]->port[1]; flw->dest_port = flows[i]->port[0]; flw->flow_packets = htonl(flows[i]->packets[1]); flw->flow_octets = htonl(flows[i]->octets[1]); flw->flow_start = htonl(timeval_sub_ms(&flows[i]->flow_start, system_boot_time)); flw->flow_finish = htonl(timeval_sub_ms(&flows[i]->flow_last, system_boot_time)); flw->protocol = flows[i]->protocol; flw->tcp_flags = flows[i]->tcp_flags[1]; offset += sizeof(*flw); j++; hdr->flows++; } } /* Send any leftovers */ if (j != 0) { if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); hdr->flows = htons(hdr->flows); errsz = sizeof(err); getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); /* Clear ICMP errors */ if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; } *flows_exported += j; return (num_packets); }
08beeumerk-flow
netflow1.c
C
bsd
5,619
#!/usr/bin/perl -w # This is a Cisco NetFlow datagram collector # Netflow protocol reference: # http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm # XXX Doesn't support NetFlow 9 my $af; BEGIN { use strict; use warnings; use IO qw(Socket); use Socket; use Carp; use POSIX qw(strftime); use Getopt::Long; eval "use IO::Socket::INET6;"; eval "use Socket6;"; } ############################################################################ sub timestamp() { return strftime "%Y-%m-%dT%H:%M:%S", localtime; } sub fuptime($) { my $t = shift; my $r = ""; my $tmp; # Milliseconds $tmp = $t % 1000; $r = sprintf ".%03u%s", $tmp, $r; # Seconds $t = int($t / 1000); $tmp = $t % 60; $r = "${tmp}s${r}"; # Minutes $t = int($t / 60); $tmp = $t % 60; $r = "${tmp}m${r}" if $tmp; # Hours $t = int($t / 60); $tmp = $t % 24; $r = "${tmp}h${r}" if $tmp; # Days $t = int($t / 24); $tmp = $t % 7; $r = "${tmp}d${r}" if $tmp; # Weeks $t = int($t / 7); $tmp = $t % 52; $r = "${tmp}w${r}" if $tmp; # Years $t = int($t / 52); $r = "${tmp}y${r}" if $tmp; return $r; } sub do_listen($$) { my $port = shift or confess "No UDP port specified"; my $socket; if ($af == 4) { $socket = IO::Socket::INET->new(Proto=>'udp', LocalPort=>$port) or croak "Couldn't open UDP socket: $!"; } elsif ($af == 6) { $socket = IO::Socket::INET6->new(Proto=>'udp', LocalPort=>$port) or croak "Couldn't open UDP socket: $!"; } else { croak "Unsupported AF"; } return $socket; } sub process_nf_v1($$) { my $sender = shift; my $pkt = shift; my %header; my %flow; my $sender_s; %header = qw(); $sender_s = inet_ntoa($sender) if $af == 4; $sender_s = inet_ntop(AF_INET6, $sender) if $af == 6; ($header{ver}, $header{flows}, $header{uptime}, $header{secs}, $header{nsecs}) = unpack("nnNNN", $pkt); if (length($pkt) < (16 + (48 * $header{flows}))) { printf STDERR timestamp()." Short Netflow v.1 packet: %d < %d\n", length($pkt), 16 + (48 * $header{flows}); return; } printf timestamp() . " HEADER v.%u (%u flow%s)\n", $header{ver}, $header{flows}, $header{flows} == 1 ? "" : "s"; for(my $i = 0; $i < $header{flows}; $i++) { my $off = 16 + (48 * $i); my $ptr = substr($pkt, $off, 52); %flow = qw(); (my $src1, my $src2, my $src3, my $src4, my $dst1, my $dst2, my $dst3, my $dst4, my $nxt1, my $nxt2, my $nxt3, my $nxt4, $flow{in_ndx}, $flow{out_ndx}, $flow{pkts}, $flow{bytes}, $flow{start}, $flow{finish}, $flow{src_port}, $flow{dst_port}, my $pad1, $flow{protocol}, $flow{tos}, $flow{tcp_flags}) = unpack("CCCCCCCCCCCCnnNNNNnnnCCC", $ptr); $flow{src} = sprintf "%u.%u.%u.%u", $src1, $src2, $src3, $src4; $flow{dst} = sprintf "%u.%u.%u.%u", $dst1, $dst2, $dst3, $dst4; $flow{nxt} = sprintf "%u.%u.%u.%u", $nxt1, $nxt2, $nxt3, $nxt4; printf timestamp() . " " . "from %s started %s finish %s proto %u %s:%u > %s:%u %u " . "packets %u octets\n", $sender_s, fuptime($flow{start}), fuptime($flow{finish}), $flow{protocol}, $flow{src}, $flow{src_port}, $flow{dst}, $flow{dst_port}, $flow{pkts}, $flow{bytes}; } } sub process_nf_v5($$) { my $sender = shift; my $pkt = shift; my %header; my %flow; my $sender_s; %header = qw(); $sender_s = inet_ntoa($sender) if $af == 4; $sender_s = inet_ntop(AF_INET6, $sender) if $af == 6; ($header{ver}, $header{flows}, $header{uptime}, $header{secs}, $header{nsecs}, $header{flow_seq}, ) = unpack("nnNNNN", $pkt); if (length($pkt) < (24 + (48 * $header{flows}))) { printf STDERR timestamp()." Short Netflow v.1 packet: %d < %d\n", length($pkt), 24 + (48 * $header{flows}); return; } printf timestamp() . " HEADER v.%u (%u flow%s) seq %u\n", $header{ver}, $header{flows}, $header{flows} == 1 ? "" : "s", $header{flow_seq}; for(my $i = 0; $i < $header{flows}; $i++) { my $off = 24 + (48 * $i); my $ptr = substr($pkt, $off, 52); %flow = qw(); (my $src1, my $src2, my $src3, my $src4, my $dst1, my $dst2, my $dst3, my $dst4, my $nxt1, my $nxt2, my $nxt3, my $nxt4, $flow{in_ndx}, $flow{out_ndx}, $flow{pkts}, $flow{bytes}, $flow{start}, $flow{finish}, $flow{src_port}, $flow{dst_port}, my $pad1, $flow{tcp_flags}, $flow{protocol}, $flow{tos}, $flow{src_as}, $flow{dst_as}, $flow{src_mask}, $flow{dst_mask}) = unpack("CCCCCCCCCCCCnnNNNNnnCCCCnnCC", $ptr); $flow{src} = sprintf "%u.%u.%u.%u", $src1, $src2, $src3, $src4; $flow{dst} = sprintf "%u.%u.%u.%u", $dst1, $dst2, $dst3, $dst4; $flow{nxt} = sprintf "%u.%u.%u.%u", $nxt1, $nxt2, $nxt3, $nxt4; printf timestamp() . " " . "from %s started %s finish %s proto %u %s:%u > %s:%u %u " . "packets %u octets\n", $sender_s, fuptime($flow{start}), fuptime($flow{finish}), $flow{protocol}, $flow{src}, $flow{src_port}, $flow{dst}, $flow{dst_port}, $flow{pkts}, $flow{bytes}; } } ############################################################################ # Commandline options my $debug = 0; my $af4 = 0; my $af6 = 0; my $port; # Long option Short option GetOptions( 'debug+' => \$debug, 'd+' => \$debug, '4+' => \$af4, '6+' => \$af6, 'port=i' => \$port, 'p=i' => \$port); # Unbuffer output $| = 1; die "The -4 and -6 are mutually exclusive\n" if $af4 && $af6; die "You must specify a port (collector.pl -p XXX).\n" unless $port; $af4 = $af = 4 if $af4 || (!$af4 && !$af6); $af6 = $af = 6 if $af6; # These modules aren't standard everywhere, so load them only if necessary # Main loop - receive and process a packet for (;;) { my $socket; my $from; my $payload; my $ver; my $failcount = 0; my $netflow; my $junk; my $sender; # Open the listening port if we haven't already $socket = do_listen($port, $af) unless defined $socket; # Fetch a packet $from = $socket->recv($payload, 8192, 0); ($junk, $sender) = unpack_sockaddr_in($from) if $af4; ($junk, $sender) = unpack_sockaddr_in6($from) if $af6; # Reopen listening socket on error if (!defined $from) { $socket->close; undef $socket; $failcount++; die "Couldn't recv: $!\n" if ($failcount > 5); next; # Socket will be reopened at start of loop } if (length($payload) < 16) { printf STDERR timestamp()." Short packet recevied: %d < 16\n", length($payload); next; } # The version is always the first 16 bits of the packet ($ver) = unpack("n", $payload); if ($ver == 1) { process_nf_v1($sender, $payload); } elsif ($ver == 5) { process_nf_v5($sender, $payload); } else { printf STDERR timestamp()." Unsupported netflow version %d\n", $ver; next; } undef $payload; next; } exit 0;
08beeumerk-flow
collector.pl
Perl
bsd
6,726
/* * Copyright 2004 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #ifndef _LOG_H #define _LOG_H void loginit(const char *ident, int to_stderr); void logit(int level, const char *fmt,...); #endif /* _LOG_H */
08beeumerk-flow
log.h
C
bsd
1,485
/* * Copyright (c) 2001 Kevin Steves. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SFD_CONVTIME_H /* * Convert a time string into seconds; format is * a sequence of: * time[qualifier] * * Valid time qualifiers are: * <none> seconds * s|S seconds * m|M minutes * h|H hours * d|D days * w|W weeks * * Examples: * 90m 90 minutes * 1h30m 90 minutes * 2d 2 days * 1w 1 week * * Return -1 if time string is invalid. */ long int convtime(const char *s); #endif /* _SFD_CONVTIME_H */
08beeumerk-flow
convtime.h
C
bsd
1,832
/* * Copyright (c) 2002 Damien Miller. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SFD_COMMON_H #define _SFD_COMMON_H #include "config.h" #define _BSD_SOURCE /* Needed for BSD-style struct ip,tcp,udp on Linux */ #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/ip_icmp.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <grp.h> #include <netdb.h> #include <limits.h> #include <pwd.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <time.h> #if defined(HAVE_NET_BPF_H) #include <net/bpf.h> #elif defined(HAVE_PCAP_BPF_H) #include <pcap-bpf.h> #endif #if defined(HAVE_INTTYPES_H) #include <inttypes.h> #endif /* The name of the program */ #define PROGNAME "softflowd" /* The name of the program */ #define PROGVER "0.9.8" /* Default pidfile */ #define DEFAULT_PIDFILE "/var/run/" PROGNAME ".pid" /* Default control socket */ #define DEFAULT_CTLSOCK "/var/run/" PROGNAME ".ctl" #define RCSID(msg) \ static /**/const char *const flowd_rcsid[] = \ { (const char *)flowd_rcsid, "\100(#)" msg } \ #ifndef IP_OFFMASK # define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ #endif #ifndef IPV6_VERSION #define IPV6_VERSION 0x60 #endif #ifndef IPV6_VERSION_MASK #define IPV6_VERSION_MASK 0xf0 #endif #ifndef IPV6_FLOWINFO_MASK #define IPV6_FLOWINFO_MASK ntohl(0x0fffffff) #endif #ifndef IPV6_FLOWLABEL_MASK #define IPV6_FLOWLABEL_MASK ntohl(0x000fffff) #endif #ifndef _PATH_DEVNULL # define _PATH_DEVNULL "/dev/null" #endif #ifndef MIN # define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX # define MAX(a,b) (((a)>(b))?(a):(b)) #endif #ifndef offsetof # define offsetof(type, member) ((size_t) &((type *)0)->member) #endif #if defined(__GNUC__) # ifndef __dead # define __dead __attribute__((__noreturn__)) # endif # ifndef __packed # define __packed __attribute__((__packed__)) # endif #endif #if !defined(HAVE_INT8_T) && defined(OUR_CFG_INT8_T) typedef OUR_CFG_INT8_T int8_t; #endif #if !defined(HAVE_INT16_T) && defined(OUR_CFG_INT16_T) typedef OUR_CFG_INT16_T int16_t; #endif #if !defined(HAVE_INT32_T) && defined(OUR_CFG_INT32_T) typedef OUR_CFG_INT32_T int32_t; #endif #if !defined(HAVE_INT64_T) && defined(OUR_CFG_INT64_T) typedef OUR_CFG_INT64_T int64_t; #endif #if !defined(HAVE_U_INT8_T) && defined(OUR_CFG_U_INT8_T) typedef OUR_CFG_U_INT8_T u_int8_t; #endif #if !defined(HAVE_U_INT16_T) && defined(OUR_CFG_U_INT16_T) typedef OUR_CFG_U_INT16_T u_int16_t; #endif #if !defined(HAVE_U_INT32_T) && defined(OUR_CFG_U_INT32_T) typedef OUR_CFG_U_INT32_T u_int32_t; #endif #if !defined(HAVE_U_INT64_T) && defined(OUR_CFG_U_INT64_T) typedef OUR_CFG_U_INT64_T u_int64_t; #endif #ifndef HAVE_STRLCPY size_t strlcpy(char *dst, const char *src, size_t siz); #endif #ifndef HAVE_STRLCAT size_t strlcat(char *dst, const char *src, size_t siz); #endif #ifndef HAVE_CLOSEFROM void closefrom(int lowfd); #endif #ifndef HAVE_STRUCT_IP6_EXT struct ip6_ext { u_int8_t ip6e_nxt; u_int8_t ip6e_len; } __packed; #endif #endif /* _SFD_COMMON_H */
08beeumerk-flow
common.h
C
bsd
4,618
/* OPENBSD ORIGINAL: lib/libc/string/strlcat.c */ /* $OpenBSD: strlcat.c,v 1.11 2003/06/17 21:56:24 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_STRLCAT RCSID("$Id$"); #if defined(LIBC_SCCS) && !defined(lint) static char *rcsid = "$OpenBSD: strlcat.c,v 1.11 2003/06/17 21:56:24 millert Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <string.h> /* * Appends src to string dst of size siz (unlike strncat, siz is the * full size of dst, not space left). At most siz-1 characters * will be copied. Always NUL terminates (unless siz <= strlen(dst)). * Returns strlen(src) + MIN(siz, strlen(initial dst)). * If retval >= siz, truncation occurred. */ size_t strlcat(char *dst, const char *src, size_t siz) { register char *d = dst; register const char *s = src; register size_t n = siz; size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; if (n == 0) return(dlen + strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return(dlen + (s - src)); /* count does not include NUL */ } #endif /* !HAVE_STRLCAT */
08beeumerk-flow
strlcat.c
C
bsd
2,012
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #include "common.h" #include "log.h" #include "treetype.h" #include "softflowd.h" RCSID("$Id$"); /* Netflow v.9 */ struct NF9_HEADER { u_int16_t version, flows; u_int32_t uptime_ms, time_sec; u_int32_t package_sequence, source_id; } __packed; struct NF9_FLOWSET_HEADER_COMMON { u_int16_t flowset_id, length; } __packed; struct NF9_TEMPLATE_FLOWSET_HEADER { struct NF9_FLOWSET_HEADER_COMMON c; u_int16_t template_id, count; } __packed; struct NF9_TEMPLATE_FLOWSET_RECORD { u_int16_t type, length; } __packed; struct NF9_DATA_FLOWSET_HEADER { struct NF9_FLOWSET_HEADER_COMMON c; } __packed; #define NF9_TEMPLATE_FLOWSET_ID 0 #define NF9_OPTIONS_FLOWSET_ID 1 #define NF9_MIN_RECORD_FLOWSET_ID 256 /* Flowset record types the we care about */ #define NF9_IN_BYTES 1 #define NF9_IN_PACKETS 2 /* ... */ #define NF9_IN_PROTOCOL 4 /* ... */ #define NF9_TCP_FLAGS 6 #define NF9_L4_SRC_PORT 7 #define NF9_IPV4_SRC_ADDR 8 /* ... */ #define NF9_IF_INDEX_IN 10 #define NF9_L4_DST_PORT 11 #define NF9_IPV4_DST_ADDR 12 /* ... */ #define NF9_IF_INDEX_OUT 14 /* ... */ #define NF9_LAST_SWITCHED 21 #define NF9_FIRST_SWITCHED 22 /* ... */ #define NF9_IPV6_SRC_ADDR 27 #define NF9_IPV6_DST_ADDR 28 /* ... */ #define NF9_IP_PROTOCOL_VERSION 60 /* Stuff pertaining to the templates that softflowd uses */ #define NF9_SOFTFLOWD_TEMPLATE_NRECORDS 11 struct NF9_SOFTFLOWD_TEMPLATE { struct NF9_TEMPLATE_FLOWSET_HEADER h; struct NF9_TEMPLATE_FLOWSET_RECORD r[NF9_SOFTFLOWD_TEMPLATE_NRECORDS]; } __packed; /* softflowd data flowset types */ struct NF9_SOFTFLOWD_DATA_COMMON { u_int32_t last_switched, first_switched; u_int32_t bytes, packets; u_int32_t if_index_in, if_index_out; u_int16_t src_port, dst_port; u_int8_t protocol, tcp_flags, ipproto; } __packed; struct NF9_SOFTFLOWD_DATA_V4 { u_int32_t src_addr, dst_addr; struct NF9_SOFTFLOWD_DATA_COMMON c; } __packed; struct NF9_SOFTFLOWD_DATA_V6 { u_int8_t src_addr[16], dst_addr[16]; struct NF9_SOFTFLOWD_DATA_COMMON c; } __packed; /* Local data: templates and counters */ #define NF9_SOFTFLOWD_MAX_PACKET_SIZE 512 #define NF9_SOFTFLOWD_V4_TEMPLATE_ID 1024 #define NF9_SOFTFLOWD_V6_TEMPLATE_ID 2048 #define NF9_DEFAULT_TEMPLATE_INTERVAL 16 static struct NF9_SOFTFLOWD_TEMPLATE v4_template; static struct NF9_SOFTFLOWD_TEMPLATE v6_template; static int nf9_pkts_until_template = -1; static void nf9_init_template(void) { bzero(&v4_template, sizeof(v4_template)); v4_template.h.c.flowset_id = htons(0); v4_template.h.c.length = htons(sizeof(v4_template)); v4_template.h.template_id = htons(NF9_SOFTFLOWD_V4_TEMPLATE_ID); v4_template.h.count = htons(NF9_SOFTFLOWD_TEMPLATE_NRECORDS); v4_template.r[0].type = htons(NF9_IPV4_SRC_ADDR); v4_template.r[0].length = htons(4); v4_template.r[1].type = htons(NF9_IPV4_DST_ADDR); v4_template.r[1].length = htons(4); v4_template.r[2].type = htons(NF9_LAST_SWITCHED); v4_template.r[2].length = htons(4); v4_template.r[3].type = htons(NF9_FIRST_SWITCHED); v4_template.r[3].length = htons(4); v4_template.r[4].type = htons(NF9_IN_BYTES); v4_template.r[4].length = htons(4); v4_template.r[5].type = htons(NF9_IN_PACKETS); v4_template.r[5].length = htons(4); v4_template.r[6].type = htons(NF9_IF_INDEX_IN); v4_template.r[6].length = htons(4); v4_template.r[7].type = htons(NF9_IF_INDEX_OUT); v4_template.r[7].length = htons(4); v4_template.r[8].type = htons(NF9_L4_SRC_PORT); v4_template.r[8].length = htons(2); v4_template.r[9].type = htons(NF9_L4_DST_PORT); v4_template.r[9].length = htons(2); v4_template.r[10].type = htons(NF9_IN_PROTOCOL); v4_template.r[10].length = htons(1); v4_template.r[11].type = htons(NF9_TCP_FLAGS); v4_template.r[11].length = htons(1); v4_template.r[12].type = htons(NF9_IP_PROTOCOL_VERSION); v4_template.r[12].length = htons(1); bzero(&v6_template, sizeof(v6_template)); v6_template.h.c.flowset_id = htons(0); v6_template.h.c.length = htons(sizeof(v6_template)); v6_template.h.template_id = htons(NF9_SOFTFLOWD_V6_TEMPLATE_ID); v6_template.h.count = htons(NF9_SOFTFLOWD_TEMPLATE_NRECORDS); v6_template.r[0].type = htons(NF9_IPV6_SRC_ADDR); v6_template.r[0].length = htons(16); v6_template.r[1].type = htons(NF9_IPV6_DST_ADDR); v6_template.r[1].length = htons(16); v6_template.r[2].type = htons(NF9_LAST_SWITCHED); v6_template.r[2].length = htons(4); v6_template.r[3].type = htons(NF9_FIRST_SWITCHED); v6_template.r[3].length = htons(4); v6_template.r[4].type = htons(NF9_IN_BYTES); v6_template.r[4].length = htons(4); v6_template.r[5].type = htons(NF9_IN_PACKETS); v6_template.r[5].length = htons(4); v4_template.r[6].type = htons(NF9_IF_INDEX_IN); v4_template.r[6].length = htons(4); v4_template.r[7].type = htons(NF9_IF_INDEX_OUT); v4_template.r[7].length = htons(4); v6_template.r[8].type = htons(NF9_L4_SRC_PORT); v6_template.r[8].length = htons(2); v6_template.r[9].type = htons(NF9_L4_DST_PORT); v6_template.r[9].length = htons(2); v6_template.r[10].type = htons(NF9_IN_PROTOCOL); v6_template.r[10].length = htons(1); v6_template.r[11].type = htons(NF9_TCP_FLAGS); v6_template.r[11].length = htons(1); v6_template.r[12].type = htons(NF9_IP_PROTOCOL_VERSION); v6_template.r[12].length = htons(1); } static int nf_flow_to_flowset(const struct FLOW *flow, u_char *packet, u_int len, u_int16_t ifidx, const struct timeval *system_boot_time, u_int *len_used) { union { struct NF9_SOFTFLOWD_DATA_V4 d4; struct NF9_SOFTFLOWD_DATA_V6 d6; } d[2]; struct NF9_SOFTFLOWD_DATA_COMMON *dc[2]; u_int freclen, ret_len, nflows; bzero(d, sizeof(d)); *len_used = nflows = ret_len = 0; switch (flow->af) { case AF_INET: freclen = sizeof(struct NF9_SOFTFLOWD_DATA_V4); memcpy(&d[0].d4.src_addr, &flow->addr[0].v4, 4); memcpy(&d[0].d4.dst_addr, &flow->addr[1].v4, 4); memcpy(&d[1].d4.src_addr, &flow->addr[1].v4, 4); memcpy(&d[1].d4.dst_addr, &flow->addr[0].v4, 4); dc[0] = &d[0].d4.c; dc[1] = &d[1].d4.c; dc[0]->ipproto = dc[1]->ipproto = 4; break; case AF_INET6: freclen = sizeof(struct NF9_SOFTFLOWD_DATA_V6); memcpy(&d[0].d6.src_addr, &flow->addr[0].v6, 16); memcpy(&d[0].d6.dst_addr, &flow->addr[1].v6, 16); memcpy(&d[1].d6.src_addr, &flow->addr[1].v6, 16); memcpy(&d[1].d6.dst_addr, &flow->addr[0].v6, 16); dc[0] = &d[0].d6.c; dc[1] = &d[1].d6.c; dc[0]->ipproto = dc[1]->ipproto = 6; break; default: return (-1); } dc[0]->first_switched = dc[1]->first_switched = htonl(timeval_sub_ms(&flow->flow_start, system_boot_time)); dc[0]->last_switched = dc[1]->last_switched = htonl(timeval_sub_ms(&flow->flow_last, system_boot_time)); dc[0]->bytes = htonl(flow->octets[0]); dc[1]->bytes = htonl(flow->octets[1]); dc[0]->packets = htonl(flow->packets[0]); dc[1]->packets = htonl(flow->packets[1]); dc[0]->if_index_in = dc[0]->if_index_out = htonl(ifidx); dc[1]->if_index_in = dc[1]->if_index_out = htonl(ifidx); dc[0]->src_port = dc[1]->dst_port = flow->port[0]; dc[1]->src_port = dc[0]->dst_port = flow->port[1]; dc[0]->protocol = dc[1]->protocol = flow->protocol; dc[0]->tcp_flags = flow->tcp_flags[0]; dc[1]->tcp_flags = flow->tcp_flags[1]; if (flow->octets[0] > 0) { if (ret_len + freclen > len) return (-1); memcpy(packet + ret_len, &d[0], freclen); ret_len += freclen; nflows++; } if (flow->octets[1] > 0) { if (ret_len + freclen > len) return (-1); memcpy(packet + ret_len, &d[1], freclen); ret_len += freclen; nflows++; } *len_used = ret_len; return (nflows); } /* * Given an array of expired flows, send netflow v9 report packets * Returns number of packets sent or -1 on error */ int send_netflow_v9(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag) { struct NF9_HEADER *nf9; struct NF9_DATA_FLOWSET_HEADER *dh; struct timeval now; u_int offset, last_af, i, j, num_packets, inc, last_valid; socklen_t errsz; int err, r; u_char packet[NF9_SOFTFLOWD_MAX_PACKET_SIZE]; gettimeofday(&now, NULL); if (nf9_pkts_until_template == -1) { nf9_init_template(); nf9_pkts_until_template = 0; } last_valid = num_packets = 0; for (j = 0; j < num_flows;) { bzero(packet, sizeof(packet)); nf9 = (struct NF9_HEADER *)packet; nf9->version = htons(9); nf9->flows = 0; /* Filled as we go, htons at end */ nf9->uptime_ms = htonl(timeval_sub_ms(&now, system_boot_time)); nf9->time_sec = htonl(time(NULL)); nf9->package_sequence = htonl(*flows_exported + j); nf9->source_id = 0; offset = sizeof(*nf9); /* Refresh template headers if we need to */ if (nf9_pkts_until_template <= 0) { memcpy(packet + offset, &v4_template, sizeof(v4_template)); offset += sizeof(v4_template); memcpy(packet + offset, &v6_template, sizeof(v6_template)); offset += sizeof(v6_template); nf9_pkts_until_template = NF9_DEFAULT_TEMPLATE_INTERVAL; } dh = NULL; last_af = 0; for (i = 0; i + j < num_flows; i++) { if (dh == NULL || flows[i + j]->af != last_af) { if (dh != NULL) { if (offset % 4 != 0) { /* Pad to multiple of 4 */ dh->c.length += 4 - (offset % 4); offset += 4 - (offset % 4); } /* Finalise last header */ dh->c.length = htons(dh->c.length); } if (offset + sizeof(*dh) > sizeof(packet)) { /* Mark header is finished */ dh = NULL; break; } dh = (struct NF9_DATA_FLOWSET_HEADER *) (packet + offset); dh->c.flowset_id = (flows[i + j]->af == AF_INET) ? v4_template.h.template_id : v6_template.h.template_id; last_af = flows[i + j]->af; last_valid = offset; dh->c.length = sizeof(*dh); /* Filled as we go */ offset += sizeof(*dh); } r = nf_flow_to_flowset(flows[i + j], packet + offset, sizeof(packet) - offset, ifidx, system_boot_time, &inc); if (r <= 0) { /* yank off data header, if we had to go back */ if (last_valid) offset = last_valid; break; } offset += inc; dh->c.length += inc; nf9->flows += r; last_valid = 0; /* Don't clobber this header now */ if (verbose_flag) { logit(LOG_DEBUG, "Flow %d/%d: " "r %d offset %d type %04x len %d(0x%04x) " "flows %d", r, i, j, offset, dh->c.flowset_id, dh->c.length, dh->c.length, nf9->flows); } } /* Don't finish header if it has already been done */ if (dh != NULL) { if (offset % 4 != 0) { /* Pad to multiple of 4 */ dh->c.length += 4 - (offset % 4); offset += 4 - (offset % 4); } /* Finalise last header */ dh->c.length = htons(dh->c.length); } nf9->flows = htons(nf9->flows); if (verbose_flag) logit(LOG_DEBUG, "Sending flow packet len = %d", offset); errsz = sizeof(err); /* Clear ICMP errors */ getsockopt(nfsock, SOL_SOCKET, SO_ERROR, &err, &errsz); if (send(nfsock, packet, (size_t)offset, 0) == -1) return (-1); num_packets++; nf9_pkts_until_template--; j += i; } *flows_exported += j; return (num_packets); } void netflow9_resend_template(void) { if (nf9_pkts_until_template > 0) nf9_pkts_until_template = 0; }
08beeumerk-flow
netflow9.c
C
bsd
12,460
# $Id$ prefix=@prefix@ exec_prefix=@exec_prefix@ bindir=@bindir@ sbindir=@sbindir@ libexecdir=@libexecdir@ datadir=@datadir@ mandir=@mandir@ sysconfdir=@sysconfdir@ srcdir=@srcdir@ top_srcdir=@top_srcdir@ VPATH=@srcdir@ CC=@CC@ LDFLAGS=@LDFLAGS@ CFLAGS=@CFLAGS@ CPPFLAGS=-I$(srcdir) @CPPFLAGS@ LIBS=@LIBS@ EXEEXT=@EXEEXT@ INSTALL=@INSTALL@ #CFLAGS+=-DFLOW_RB # Use red-black tree for flows CFLAGS+=-DFLOW_SPLAY # Use splay tree for flows CFLAGS+=-DEXPIRY_RB # Use red-black tree for expiry events #CFLAGS+=-DEXPIRY_SPLAY # Use splay tree for expiry events TARGETS=softflowd${EXEEXT} softflowctl${EXEEXT} COMMON=convtime.o strlcpy.o strlcat.o closefrom.o daemon.o SOFTFLOWD=softflowd.o log.o netflow1.o netflow5.o netflow9.o freelist.o all: $(TARGETS) softflowd${EXEEXT}: ${SOFTFLOWD} $(COMMON) $(CC) $(LDFLAGS) -o $@ ${SOFTFLOWD} $(COMMON) $(LIBS) softflowctl${EXEEXT}: softflowctl.o $(COMMON) $(CC) $(LDFLAGS) -o $@ softflowctl.o $(COMMON) $(LIBS) clean: rm -f $(TARGETS) *.o core *.core realclean: clean rm -rf autom4te.cache Makefile config.log config.status distclean: realclean rm -f config.h* configure strip: strip $(TARGETS) install: [ -d $(DESTDIR)$(sbindir) ] || \ $(srcdir)/mkinstalldirs $(DESTDIR)$(sbindir) [ -d $(DESTDIR)$(mandir)/man8 ] || \ $(srcdir)/mkinstalldirs $(DESTDIR)$(mandir)/man8 $(INSTALL) -m 0755 -s softflowd $(DESTDIR)$(sbindir)/softflowd $(INSTALL) -m 0755 -s softflowctl $(DESTDIR)$(sbindir)/softflowctl $(INSTALL) -m 0644 softflowd.8 $(DESTDIR)$(mandir)/man8/softflowd.8 $(INSTALL) -m 0644 softflowctl.8 $(DESTDIR)$(mandir)/man8/softflowctl.8
08beeumerk-flow
Makefile.in
Makefile
bsd
1,614
#!/bin/sh # # install - install a program, script, or datafile # This comes from X11R5 (mit/util/scripts/install.sh). # # Copyright 1991 by the Massachusetts Institute of Technology # # Permission to use, copy, modify, distribute, and sell this software and its # documentation for any purpose is hereby granted without fee, provided that # the above copyright notice appear in all copies and that both that # copyright notice and this permission notice appear in supporting # documentation, and that the name of M.I.T. not be used in advertising or # publicity pertaining to distribution of the software without specific, # written prior permission. M.I.T. makes no representations about the # suitability of this software for any purpose. It is provided "as is" # without express or implied warranty. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. It can only install one file at a time, a restriction # shared with many OS's install programs. # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit="${DOITPROG-}" # put in absolute paths if you don't have them in your path; or use env. vars. mvprog="${MVPROG-mv}" cpprog="${CPPROG-cp}" chmodprog="${CHMODPROG-chmod}" chownprog="${CHOWNPROG-chown}" chgrpprog="${CHGRPPROG-chgrp}" stripprog="${STRIPPROG-strip}" rmprog="${RMPROG-rm}" mkdirprog="${MKDIRPROG-mkdir}" transformbasename="" transform_arg="" instcmd="$mvprog" chmodcmd="$chmodprog 0755" chowncmd="" chgrpcmd="" stripcmd="" rmcmd="$rmprog -f" mvcmd="$mvprog" src="" dst="" dir_arg="" while [ x"$1" != x ]; do case $1 in -c) instcmd="$cpprog" shift continue;; -d) dir_arg=true shift continue;; -m) chmodcmd="$chmodprog $2" shift shift continue;; -o) chowncmd="$chownprog $2" shift shift continue;; -g) chgrpcmd="$chgrpprog $2" shift shift continue;; -s) stripcmd="$stripprog" shift continue;; -t=*) transformarg=`echo $1 | sed 's/-t=//'` shift continue;; -b=*) transformbasename=`echo $1 | sed 's/-b=//'` shift continue;; *) if [ x"$src" = x ] then src=$1 else # this colon is to work around a 386BSD /bin/sh bug : dst=$1 fi shift continue;; esac done if [ x"$src" = x ] then echo "install: no input file specified" exit 1 else true fi if [ x"$dir_arg" != x ]; then dst=$src src="" if [ -d $dst ]; then instcmd=: chmodcmd="" else instcmd=mkdir fi else # Waiting for this to be detected by the "$instcmd $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if [ -f $src -o -d $src ] then true else echo "install: $src does not exist" exit 1 fi if [ x"$dst" = x ] then echo "install: no destination specified" exit 1 else true fi # If destination is a directory, append the input filename; if your system # does not like double slashes in filenames, you may need to add some logic if [ -d $dst ] then dst="$dst"/`basename $src` else true fi fi ## this sed command emulates the dirname command dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` # Make sure that the destination directory exists. # this part is taken from Noah Friedman's mkinstalldirs script # Skip lots of stat calls in the usual case. if [ ! -d "$dstdir" ]; then defaultIFS=' ' IFS="${IFS-${defaultIFS}}" oIFS="${IFS}" # Some sh's can't handle IFS=/ for some reason. IFS='%' set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` IFS="${oIFS}" pathcomp='' while [ $# -ne 0 ] ; do pathcomp="${pathcomp}${1}" shift if [ ! -d "${pathcomp}" ] ; then $mkdirprog "${pathcomp}" else true fi pathcomp="${pathcomp}/" done fi if [ x"$dir_arg" != x ] then $doit $instcmd $dst && if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi else # If we're going to rename the final executable, determine the name now. if [ x"$transformarg" = x ] then dstfile=`basename $dst` else dstfile=`basename $dst $transformbasename | sed $transformarg`$transformbasename fi # don't allow the sed command to completely eliminate the filename if [ x"$dstfile" = x ] then dstfile=`basename $dst` else true fi # Make a temp file name in the proper directory. dsttmp=$dstdir/#inst.$$# # Move or copy the file name to the temp name $doit $instcmd $src $dsttmp && trap "rm -f ${dsttmp}" 0 && # and set any options; do chmod last to preserve setuid bits # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $instcmd $src $dsttmp" command. if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && # Now rename the file to the real destination. $doit $rmcmd -f $dstdir/$dstfile && $doit $mvcmd $dsttmp $dstdir/$dstfile fi && exit 0
08beeumerk-flow
install-sh
Shell
bsd
5,586
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" RCSID("$Id$"); static void usage(void) { fprintf(stderr, "Usage: [-c ctlsock] softflowctl [command]\n"); } int main(int argc, char **argv) { const char *ctlsock_path; char buf[8192], *command; struct sockaddr_un ctl; socklen_t ctllen; int ctlsock, ch; FILE *ctlf; extern char *optarg; extern int optind; ctlsock_path = DEFAULT_CTLSOCK; while ((ch = getopt(argc, argv, "hc:")) != -1) { switch (ch) { case 'h': usage(); return (0); case 'c': ctlsock_path = optarg; break; default: fprintf(stderr, "Invalid commandline option.\n"); usage(); exit(1); } } /* Accept only one argument */ if (optind != argc - 1) { usage(); exit(1); } command = argv[optind]; memset(&ctl, '\0', sizeof(ctl)); if (strlcpy(ctl.sun_path, ctlsock_path, sizeof(ctl.sun_path)) >= sizeof(ctl.sun_path)) { fprintf(stderr, "Control socket path too long.\n"); exit(1); } ctl.sun_path[sizeof(ctl.sun_path) - 1] = '\0'; ctl.sun_family = AF_UNIX; ctllen = offsetof(struct sockaddr_un, sun_path) + strlen(ctlsock_path) + 1; #ifdef SOCK_HAS_LEN ctl.sun_len = ctllen; #endif if ((ctlsock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "ctl socket() error: %s\n", strerror(errno)); exit(1); } if (connect(ctlsock, (struct sockaddr*)&ctl, sizeof(ctl)) == -1) { fprintf(stderr, "ctl connect(\"%s\") error: %s\n", ctl.sun_path, strerror(errno)); exit(1); } if ((ctlf = fdopen(ctlsock, "r+")) == NULL) { fprintf(stderr, "fdopen: %s\n", strerror(errno)); exit(1); } setlinebuf(ctlf); /* Send command */ if (fprintf(ctlf, "%s\n", command) < 0) { fprintf(stderr, "write: %s\n", strerror(errno)); exit(1); } /* Write out reply */ while((fgets(buf, sizeof(buf), ctlf)) != NULL) fputs(buf, stdout); fclose(ctlf); close(ctlsock); exit(0); }
08beeumerk-flow
softflowctl.c
C
bsd
3,190
/* * Copyright (c) 2007 Damien Miller. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FREELIST_H #define _FREELIST_H #include "common.h" /* Simple freelist of fixed-sized allocations */ struct freelist { size_t allocsz; size_t nalloc; size_t navail; void **free_entries; }; /* * Initialise a freelist. * allocsz is the size of the individual allocations */ void freelist_init(struct freelist *freelist, size_t allocsz); /* * Get an entry from a freelist. * Will allocate new entries if necessary * Returns pointer to allocated memory or NULL on failure. */ void *freelist_get(struct freelist *freelist); /* * Returns an entry to the freelist. * p must be a pointer to an allocation from the freelist. */ void freelist_put(struct freelist *freelist, void *p); #endif /* FREELIST_H */
08beeumerk-flow
freelist.h
C
bsd
2,044
/* * Copyright 2004 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ #include "common.h" #include "log.h" #include <stdarg.h> RCSID("$Id$"); static int logstderr = 0; void loginit(const char *ident, int to_stderr) { if (to_stderr) logstderr = 1; else openlog(PROGNAME, LOG_PID|LOG_NDELAY, LOG_DAEMON); } void logit(int level, const char *fmt,...) { va_list args; va_start(args, fmt); if (logstderr) { vfprintf(stderr, fmt, args); fputs("\n", stderr); } else vsyslog(level, fmt, args); va_end(args); }
08beeumerk-flow
log.c
C
bsd
1,798
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ /* * This is software implementation of Cisco's NetFlow(tm) traffic * reporting system. It operates by listening (via libpcap) on a * promiscuous interface and tracking traffic flows. * * Traffic flows are recorded by source/destination/protocol * IP address or, in the case of TCP and UDP, by * src_addr:src_port/dest_addr:dest_port/protocol * * Flows expire automatically after a period of inactivity (default: 1 * hour) They may also be evicted (in order of age) in situations where * there are more flows than slots available. * * Netflow compatible packets are sent to a specified target host upon * flow expiry. * * As this implementation watches traffic promiscuously, it is likely to * place significant load on hosts or gateways on which it is installed. */ #include "common.h" #include "sys-tree.h" #include "convtime.h" #include "softflowd.h" #include "treetype.h" #include "freelist.h" #include "log.h" #include <pcap.h> RCSID("$Id$"); /* Global variables */ static int verbose_flag = 0; /* Debugging flag */ static u_int16_t if_index = 0; /* "manual" interface index */ /* Signal handler flags */ static volatile sig_atomic_t graceful_shutdown_request = 0; /* Context for libpcap callback functions */ struct CB_CTXT { struct FLOWTRACK *ft; int linktype; int fatal; int want_v6; }; /* Describes a datalink header and how to extract v4/v6 frames from it */ struct DATALINK { int dlt; /* BPF datalink type */ int skiplen; /* Number of bytes to skip datalink header */ int ft_off; /* Datalink frametype offset */ int ft_len; /* Datalink frametype length */ int ft_is_be; /* Set if frametype is big-endian */ u_int32_t ft_mask; /* Mask applied to frametype */ u_int32_t ft_v4; /* IPv4 frametype */ u_int32_t ft_v6; /* IPv6 frametype */ }; /* Datalink types that we know about */ static const struct DATALINK lt[] = { { DLT_EN10MB, 14, 12, 2, 1, 0xffffffff, 0x0800, 0x86dd }, { DLT_PPP, 5, 3, 2, 1, 0xffffffff, 0x0021, 0x0057 }, #ifdef DLT_LINUX_SLL { DLT_LINUX_SLL,16, 14, 2, 1, 0xffffffff, 0x0800, 0x86dd }, #endif { DLT_RAW, 0, 0, 1, 1, 0x000000f0, 0x0040, 0x0060 }, { DLT_NULL, 4, 0, 4, 0, 0xffffffff, AF_INET, AF_INET6 }, #ifdef DLT_LOOP { DLT_LOOP, 4, 0, 4, 1, 0xffffffff, AF_INET, AF_INET6 }, #endif { -1, -1, -1, -1, -1, 0x00000000, 0xffff, 0xffff }, }; /* Netflow send functions */ typedef int (netflow_send_func_t)(struct FLOW **, int, int, u_int16_t, u_int64_t *, struct timeval *, int); struct NETFLOW_SENDER { int version; netflow_send_func_t *func; int v6_capable; }; /* Array of NetFlow export function that we know of. NB. nf[0] is default */ static const struct NETFLOW_SENDER nf[] = { { 5, send_netflow_v5, 0 }, { 1, send_netflow_v1, 0 }, { 9, send_netflow_v9, 1 }, { -1, NULL, 0 }, }; /* Describes a location where we send NetFlow packets to */ struct NETFLOW_TARGET { int fd; const struct NETFLOW_SENDER *dialect; }; /* Signal handlers */ static void sighand_graceful_shutdown(int signum) { graceful_shutdown_request = signum; } static void sighand_other(int signum) { /* XXX: this may not be completely safe */ logit(LOG_WARNING, "Exiting immediately on unexpected signal %d", signum); _exit(0); } /* * This is the flow comparison function. */ static int flow_compare(struct FLOW *a, struct FLOW *b) { /* Be careful to avoid signed vs unsigned issues here */ int r; if (a->af != b->af) return (a->af > b->af ? 1 : -1); if ((r = memcmp(&a->addr[0], &b->addr[0], sizeof(a->addr[0]))) != 0) return (r > 0 ? 1 : -1); if ((r = memcmp(&a->addr[1], &b->addr[1], sizeof(a->addr[1]))) != 0) return (r > 0 ? 1 : -1); #ifdef notyet if (a->ip6_flowlabel[0] != 0 && b->ip6_flowlabel[0] != 0 && a->ip6_flowlabel[0] != b->ip6_flowlabel[0]) return (a->ip6_flowlabel[0] > b->ip6_flowlabel[0] ? 1 : -1); if (a->ip6_flowlabel[1] != 0 && b->ip6_flowlabel[1] != 0 && a->ip6_flowlabel[1] != b->ip6_flowlabel[1]) return (a->ip6_flowlabel[1] > b->ip6_flowlabel[1] ? 1 : -1); #endif if (a->protocol != b->protocol) return (a->protocol > b->protocol ? 1 : -1); if (a->port[0] != b->port[0]) return (ntohs(a->port[0]) > ntohs(b->port[0]) ? 1 : -1); if (a->port[1] != b->port[1]) return (ntohs(a->port[1]) > ntohs(b->port[1]) ? 1 : -1); return (0); } /* Generate functions for flow tree */ FLOW_PROTOTYPE(FLOWS, FLOW, trp, flow_compare); FLOW_GENERATE(FLOWS, FLOW, trp, flow_compare); /* * This is the expiry comparison function. */ static int expiry_compare(struct EXPIRY *a, struct EXPIRY *b) { if (a->expires_at != b->expires_at) return (a->expires_at > b->expires_at ? 1 : -1); /* Make expiry entries unique by comparing flow sequence */ if (a->flow->flow_seq != b->flow->flow_seq) return (a->flow->flow_seq > b->flow->flow_seq ? 1 : -1); return (0); } /* Generate functions for flow tree */ EXPIRY_PROTOTYPE(EXPIRIES, EXPIRY, trp, expiry_compare); EXPIRY_GENERATE(EXPIRIES, EXPIRY, trp, expiry_compare); static struct FLOW * flow_get(struct FLOWTRACK *ft) { return freelist_get(&ft->flow_freelist); } static void flow_put(struct FLOWTRACK *ft, struct FLOW *flow) { return freelist_put(&ft->flow_freelist, flow); } static struct EXPIRY * expiry_get(struct FLOWTRACK *ft) { return freelist_get(&ft->expiry_freelist); } static void expiry_put(struct FLOWTRACK *ft, struct EXPIRY *expiry) { return freelist_put(&ft->expiry_freelist, expiry); } #if 0 /* Dump a packet */ static void dump_packet(const u_int8_t *p, int len) { char buf[1024], tmp[3]; int i; for (*buf = '\0', i = 0; i < len; i++) { snprintf(tmp, sizeof(tmp), "%02x%s", p[i], i % 2 ? " " : ""); if (strlcat(buf, tmp, sizeof(buf) - 4) >= sizeof(buf) - 4) { strlcat(buf, "...", sizeof(buf)); break; } } logit(LOG_INFO, "packet len %d: %s", len, buf); } #endif /* Format a time in an ISOish format */ static const char * format_time(time_t t) { struct tm *tm; static char buf[32]; tm = gmtime(&t); strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm); return (buf); } /* Format a flow in a verbose and ugly way */ static const char * format_flow(struct FLOW *flow) { char addr1[64], addr2[64], stime[32], ftime[32]; static char buf[1024]; inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1)); inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2)); snprintf(stime, sizeof(ftime), "%s", format_time(flow->flow_start.tv_sec)); snprintf(ftime, sizeof(ftime), "%s", format_time(flow->flow_last.tv_sec)); snprintf(buf, sizeof(buf), "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u " "octets>:%u packets>:%u octets<:%u packets<:%u " "start:%s.%03ld finish:%s.%03ld tcp>:%02x tcp<:%02x " "flowlabel>:%08x flowlabel<:%08x ", flow->flow_seq, addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]), (int)flow->protocol, flow->octets[0], flow->packets[0], flow->octets[1], flow->packets[1], stime, (flow->flow_start.tv_usec + 500) / 1000, ftime, (flow->flow_last.tv_usec + 500) / 1000, flow->tcp_flags[0], flow->tcp_flags[1], flow->ip6_flowlabel[0], flow->ip6_flowlabel[1]); return (buf); } /* Format a flow in a brief way */ static const char * format_flow_brief(struct FLOW *flow) { char addr1[64], addr2[64]; static char buf[1024]; inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1)); inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2)); snprintf(buf, sizeof(buf), "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u", flow->flow_seq, addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]), (int)flow->protocol); return (buf); } /* Fill in transport-layer (tcp/udp) portions of flow record */ static int transport_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, const size_t caplen, int isfrag, int protocol, int ndx) { const struct tcphdr *tcp = (const struct tcphdr *)pkt; const struct udphdr *udp = (const struct udphdr *)pkt; const struct icmp *icmp = (const struct icmp *)pkt; /* * XXX to keep flow in proper canonical format, it may be necessary to * swap the array slots based on the order of the port numbers does * this matter in practice??? I don't think so - return flows will * always match, because of their symmetrical addr/ports */ switch (protocol) { case IPPROTO_TCP: /* Check for runt packet, but don't error out on short frags */ if (caplen < sizeof(*tcp)) return (isfrag ? 0 : 1); flow->port[ndx] = tcp->th_sport; flow->port[ndx ^ 1] = tcp->th_dport; flow->tcp_flags[ndx] |= tcp->th_flags; break; case IPPROTO_UDP: /* Check for runt packet, but don't error out on short frags */ if (caplen < sizeof(*udp)) return (isfrag ? 0 : 1); flow->port[ndx] = udp->uh_sport; flow->port[ndx ^ 1] = udp->uh_dport; break; case IPPROTO_ICMP: /* * Encode ICMP type * 256 + code into dest port like * Cisco routers */ flow->port[ndx] = 0; flow->port[ndx ^ 1] = htons(icmp->icmp_type * 256 + icmp->icmp_code); break; } return (0); } /* Convert a IPv4 packet to a partial flow record (used for comparison) */ static int ipv4_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen, size_t len, int *isfrag, int af) { const struct ip *ip = (const struct ip *)pkt; int ndx; if (caplen < 20 || caplen < ip->ip_hl * 4) return (-1); /* Runt packet */ if (ip->ip_v != 4) return (-1); /* Unsupported IP version */ /* Prepare to store flow in canonical format */ ndx = memcmp(&ip->ip_src, &ip->ip_dst, sizeof(ip->ip_src)) > 0 ? 1 : 0; flow->af = af; flow->addr[ndx].v4 = ip->ip_src; flow->addr[ndx ^ 1].v4 = ip->ip_dst; flow->protocol = ip->ip_p; flow->octets[ndx] = len; flow->packets[ndx] = 1; *isfrag = (ntohs(ip->ip_off) & (IP_OFFMASK|IP_MF)) ? 1 : 0; /* Don't try to examine higher level headers if not first fragment */ if (*isfrag && (ntohs(ip->ip_off) & IP_OFFMASK) != 0) return (0); return (transport_to_flowrec(flow, pkt + (ip->ip_hl * 4), caplen - (ip->ip_hl * 4), *isfrag, ip->ip_p, ndx)); } /* Convert a IPv6 packet to a partial flow record (used for comparison) */ static int ipv6_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen, size_t len, int *isfrag, int af) { const struct ip6_hdr *ip6 = (const struct ip6_hdr *)pkt; const struct ip6_ext *eh6; const struct ip6_frag *fh6; int ndx, nxt; if (caplen < sizeof(*ip6)) return (-1); /* Runt packet */ if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) return (-1); /* Unsupported IPv6 version */ /* Prepare to store flow in canonical format */ ndx = memcmp(&ip6->ip6_src, &ip6->ip6_dst, sizeof(ip6->ip6_src)) > 0 ? 1 : 0; flow->af = af; flow->ip6_flowlabel[ndx] = ip6->ip6_flow & IPV6_FLOWLABEL_MASK; flow->addr[ndx].v6 = ip6->ip6_src; flow->addr[ndx ^ 1].v6 = ip6->ip6_dst; flow->octets[ndx] = len; flow->packets[ndx] = 1; *isfrag = 0; nxt = ip6->ip6_nxt; pkt += sizeof(*ip6); caplen -= sizeof(*ip6); /* Now loop through headers, looking for transport header */ for (;;) { eh6 = (const struct ip6_ext *)pkt; if (nxt == IPPROTO_HOPOPTS || nxt == IPPROTO_ROUTING || nxt == IPPROTO_DSTOPTS) { if (caplen < sizeof(*eh6) || caplen < (eh6->ip6e_len + 1) << 3) return (1); /* Runt */ nxt = eh6->ip6e_nxt; pkt += (eh6->ip6e_len + 1) << 3; caplen -= (eh6->ip6e_len + 1) << 3; } else if (nxt == IPPROTO_FRAGMENT) { *isfrag = 1; fh6 = (const struct ip6_frag *)eh6; if (caplen < sizeof(*fh6)) return (1); /* Runt */ /* * Don't try to examine higher level headers if * not first fragment */ if ((fh6->ip6f_offlg & IP6F_OFF_MASK) != 0) return (0); nxt = fh6->ip6f_nxt; pkt += sizeof(*fh6); caplen -= sizeof(*fh6); } else break; } flow->protocol = nxt; return (transport_to_flowrec(flow, pkt, caplen, *isfrag, nxt, ndx)); } static void flow_update_expiry(struct FLOWTRACK *ft, struct FLOW *flow) { EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry); /* Flows over 2 GiB traffic */ if (flow->octets[0] > (1U << 31) || flow->octets[1] > (1U << 31)) { flow->expiry->expires_at = 0; flow->expiry->reason = R_OVERBYTES; goto out; } /* Flows over maximum life seconds */ if (ft->maximum_lifetime != 0 && flow->flow_last.tv_sec - flow->flow_start.tv_sec > ft->maximum_lifetime) { flow->expiry->expires_at = 0; flow->expiry->reason = R_MAXLIFE; goto out; } if (flow->protocol == IPPROTO_TCP) { /* Reset TCP flows */ if (ft->tcp_rst_timeout != 0 && ((flow->tcp_flags[0] & TH_RST) || (flow->tcp_flags[1] & TH_RST))) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_rst_timeout; flow->expiry->reason = R_TCP_RST; goto out; } /* Finished TCP flows */ if (ft->tcp_fin_timeout != 0 && ((flow->tcp_flags[0] & TH_FIN) && (flow->tcp_flags[1] & TH_FIN))) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_fin_timeout; flow->expiry->reason = R_TCP_FIN; goto out; } /* TCP flows */ if (ft->tcp_timeout != 0) { flow->expiry->expires_at = flow->flow_last.tv_sec + ft->tcp_timeout; flow->expiry->reason = R_TCP; goto out; } } if (ft->udp_timeout != 0 && flow->protocol == IPPROTO_UDP) { /* UDP flows */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->udp_timeout; flow->expiry->reason = R_UDP; goto out; } if (ft->icmp_timeout != 0 && ((flow->af == AF_INET && flow->protocol == IPPROTO_ICMP) || ((flow->af == AF_INET6 && flow->protocol == IPPROTO_ICMPV6)))) { /* ICMP flows */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->icmp_timeout; flow->expiry->reason = R_ICMP; goto out; } /* Everything else */ flow->expiry->expires_at = flow->flow_last.tv_sec + ft->general_timeout; flow->expiry->reason = R_GENERAL; out: if (ft->maximum_lifetime != 0 && flow->expiry->expires_at != 0) { flow->expiry->expires_at = MIN(flow->expiry->expires_at, flow->flow_start.tv_sec + ft->maximum_lifetime); } EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry); } /* Return values from process_packet */ #define PP_OK 0 #define PP_BAD_PACKET -2 #define PP_MALLOC_FAIL -3 /* * Main per-packet processing function. Take a packet (provided by * libpcap) and attempt to find a matching flow. If no such flow exists, * then create one. * * Also marks flows for fast expiry, based on flow or packet attributes * (the actual expiry is performed elsewhere) */ static int process_packet(struct FLOWTRACK *ft, const u_int8_t *pkt, int af, const u_int32_t caplen, const u_int32_t len, const struct timeval *received_time) { struct FLOW tmp, *flow; int frag; ft->total_packets++; /* Convert the IP packet to a flow identity */ memset(&tmp, 0, sizeof(tmp)); switch (af) { case AF_INET: if (ipv4_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1) goto bad; break; case AF_INET6: if (ipv6_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1) goto bad; break; default: bad: ft->bad_packets++; return (PP_BAD_PACKET); } if (frag) ft->frag_packets++; /* Zero out bits of the flow that aren't relevant to tracking level */ switch (ft->track_level) { case TRACK_IP_ONLY: tmp.protocol = 0; /* FALLTHROUGH */ case TRACK_IP_PROTO: tmp.port[0] = tmp.port[1] = 0; tmp.tcp_flags[0] = tmp.tcp_flags[1] = 0; /* FALLTHROUGH */ case TRACK_FULL: break; } /* If a matching flow does not exist, create and insert one */ if ((flow = FLOW_FIND(FLOWS, &ft->flows, &tmp)) == NULL) { /* Allocate and fill in the flow */ if ((flow = flow_get(ft)) == NULL) { logit(LOG_ERR, "process_packet: flow_get failed", sizeof(*flow)); return (PP_MALLOC_FAIL); } memcpy(flow, &tmp, sizeof(*flow)); memcpy(&flow->flow_start, received_time, sizeof(flow->flow_start)); flow->flow_seq = ft->next_flow_seq++; FLOW_INSERT(FLOWS, &ft->flows, flow); /* Allocate and fill in the associated expiry event */ if ((flow->expiry = expiry_get(ft)) == NULL) { logit(LOG_ERR, "process_packet: expiry_get failed", sizeof(*flow->expiry)); return (PP_MALLOC_FAIL); } flow->expiry->flow = flow; /* Must be non-zero (0 means expire immediately) */ flow->expiry->expires_at = 1; flow->expiry->reason = R_GENERAL; EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry); ft->num_flows++; if (verbose_flag) logit(LOG_DEBUG, "ADD FLOW %s", format_flow_brief(flow)); } else { /* Update flow statistics */ flow->packets[0] += tmp.packets[0]; flow->octets[0] += tmp.octets[0]; flow->tcp_flags[0] |= tmp.tcp_flags[0]; flow->packets[1] += tmp.packets[1]; flow->octets[1] += tmp.octets[1]; flow->tcp_flags[1] |= tmp.tcp_flags[1]; } memcpy(&flow->flow_last, received_time, sizeof(flow->flow_last)); if (flow->expiry->expires_at != 0) flow_update_expiry(ft, flow); return (PP_OK); } /* * Subtract two timevals. Returns (t1 - t2) in milliseconds. */ u_int32_t timeval_sub_ms(const struct timeval *t1, const struct timeval *t2) { struct timeval res; res.tv_sec = t1->tv_sec - t2->tv_sec; res.tv_usec = t1->tv_usec - t2->tv_usec; if (res.tv_usec < 0) { res.tv_usec += 1000000L; res.tv_sec--; } return ((u_int32_t)res.tv_sec * 1000 + (u_int32_t)res.tv_usec / 1000); } static void update_statistic(struct STATISTIC *s, double new, double n) { if (n == 1.0) { s->min = s->mean = s->max = new; return; } s->min = MIN(s->min, new); s->max = MAX(s->max, new); s->mean = s->mean + ((new - s->mean) / n); } /* Update global statistics */ static void update_statistics(struct FLOWTRACK *ft, struct FLOW *flow) { double tmp; static double n = 1.0; ft->flows_expired++; ft->flows_pp[flow->protocol % 256]++; tmp = (double)flow->flow_last.tv_sec + ((double)flow->flow_last.tv_usec / 1000000.0); tmp -= (double)flow->flow_start.tv_sec + ((double)flow->flow_start.tv_usec / 1000000.0); if (tmp < 0.0) tmp = 0.0; update_statistic(&ft->duration, tmp, n); update_statistic(&ft->duration_pp[flow->protocol], tmp, (double)ft->flows_pp[flow->protocol % 256]); tmp = flow->octets[0] + flow->octets[1]; update_statistic(&ft->octets, tmp, n); ft->octets_pp[flow->protocol % 256] += tmp; tmp = flow->packets[0] + flow->packets[1]; update_statistic(&ft->packets, tmp, n); ft->packets_pp[flow->protocol % 256] += tmp; n++; } static void update_expiry_stats(struct FLOWTRACK *ft, struct EXPIRY *e) { switch (e->reason) { case R_GENERAL: ft->expired_general++; break; case R_TCP: ft->expired_tcp++; break; case R_TCP_RST: ft->expired_tcp_rst++; break; case R_TCP_FIN: ft->expired_tcp_fin++; break; case R_UDP: ft->expired_udp++; break; case R_ICMP: ft->expired_icmp++; break; case R_MAXLIFE: ft->expired_maxlife++; break; case R_OVERBYTES: ft->expired_overbytes++; break; case R_OVERFLOWS: ft->expired_maxflows++; break; case R_FLUSH: ft->expired_flush++; break; } } /* How long before the next expiry event in millisecond */ static int next_expire(struct FLOWTRACK *ft) { struct EXPIRY *expiry; struct timeval now; u_int32_t expires_at, ret, fudge; gettimeofday(&now, NULL); if ((expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries)) == NULL) return (-1); /* indefinite */ expires_at = expiry->expires_at; /* Don't cluster urgent expiries */ if (expires_at == 0 && (expiry->reason == R_OVERBYTES || expiry->reason == R_OVERFLOWS || expiry->reason == R_FLUSH)) return (0); /* Now */ /* Cluster expiries by expiry_interval */ if (ft->expiry_interval > 1) { if ((fudge = expires_at % ft->expiry_interval) > 0) expires_at += ft->expiry_interval - fudge; } if (expires_at < now.tv_sec) return (0); /* Now */ ret = 999 + (expires_at - now.tv_sec) * 1000; return (ret); } /* * Scan the tree of expiry events and process expired flows. If zap_all * is set, then forcibly expire all flows. */ #define CE_EXPIRE_NORMAL 0 /* Normal expiry processing */ #define CE_EXPIRE_ALL -1 /* Expire all flows immediately */ #define CE_EXPIRE_FORCED 1 /* Only expire force-expired flows */ static int check_expired(struct FLOWTRACK *ft, struct NETFLOW_TARGET *target, int ex) { struct FLOW **expired_flows, **oldexp; int num_expired, i, r; struct timeval now; struct EXPIRY *expiry, *nexpiry; gettimeofday(&now, NULL); r = 0; num_expired = 0; expired_flows = NULL; if (verbose_flag) logit(LOG_DEBUG, "Starting expiry scan: mode %d", ex); for(expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries); expiry != NULL; expiry = nexpiry) { nexpiry = EXPIRY_NEXT(EXPIRIES, &ft->expiries, expiry); if ((expiry->expires_at == 0) || (ex == CE_EXPIRE_ALL) || (ex != CE_EXPIRE_FORCED && (expiry->expires_at < now.tv_sec))) { /* Flow has expired */ if (ft->maximum_lifetime != 0 && expiry->flow->flow_last.tv_sec - expiry->flow->flow_start.tv_sec >= ft->maximum_lifetime) expiry->reason = R_MAXLIFE; if (verbose_flag) logit(LOG_DEBUG, "Queuing flow seq:%llu (%p) for expiry " "reason %d", expiry->flow->flow_seq, expiry->flow, expiry->reason); /* Add to array of expired flows */ oldexp = expired_flows; expired_flows = realloc(expired_flows, sizeof(*expired_flows) * (num_expired + 1)); /* Don't fatal on realloc failures */ if (expired_flows == NULL) expired_flows = oldexp; else { expired_flows[num_expired] = expiry->flow; num_expired++; } if (ex == CE_EXPIRE_ALL) expiry->reason = R_FLUSH; update_expiry_stats(ft, expiry); /* Remove from flow tree, destroy expiry event */ FLOW_REMOVE(FLOWS, &ft->flows, expiry->flow); EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiry); expiry->flow->expiry = NULL; expiry_put(ft, expiry); ft->num_flows--; } } if (verbose_flag) logit(LOG_DEBUG, "Finished scan %d flow(s) to be evicted", num_expired); /* Processing for expired flows */ if (num_expired > 0) { if (target != NULL && target->fd != -1) { r = target->dialect->func(expired_flows, num_expired, target->fd, if_index, &ft->flows_exported, &ft->system_boot_time, verbose_flag); if (verbose_flag) logit(LOG_DEBUG, "sent %d netflow packets", r); if (r > 0) { ft->packets_sent += r; /* XXX what if r < num_expired * 2 ? */ } else { ft->flows_dropped += num_expired * 2; } } for (i = 0; i < num_expired; i++) { if (verbose_flag) { logit(LOG_DEBUG, "EXPIRED: %s (%p)", format_flow(expired_flows[i]), expired_flows[i]); } update_statistics(ft, expired_flows[i]); flow_put(ft, expired_flows[i]); } free(expired_flows); } return (r == -1 ? -1 : num_expired); } /* * Force expiry of num_to_expire flows (e.g. when flow table overfull) */ static void force_expire(struct FLOWTRACK *ft, u_int32_t num_to_expire) { struct EXPIRY *expiry, **expiryv; int i; /* XXX move all overflow processing here (maybe) */ if (verbose_flag) logit(LOG_INFO, "Forcing expiry of %d flows", num_to_expire); /* * Do this in two steps, as it is dangerous to change a key on * a tree entry without first removing it and then re-adding it. * It is even worse when this has to be done during a FOREACH :) * To get around this, we make a list of expired flows and _then_ * alter them */ if ((expiryv = calloc(num_to_expire, sizeof(*expiryv))) == NULL) { /* * On malloc failure, expire ALL flows. I assume that * setting all the keys in a tree to the same value is * safe. */ logit(LOG_ERR, "Out of memory while expiring flows - " "all flows expired"); EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { expiry->expires_at = 0; expiry->reason = R_OVERFLOWS; ft->flows_force_expired++; } return; } /* Make the list of flows to expire */ i = 0; EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { if (i >= num_to_expire) break; expiryv[i++] = expiry; } if (i < num_to_expire) { logit(LOG_ERR, "Needed to expire %d flows, " "but only %d active", num_to_expire, i); num_to_expire = i; } for(i = 0; i < num_to_expire; i++) { EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiryv[i]); expiryv[i]->expires_at = 0; expiryv[i]->reason = R_OVERFLOWS; EXPIRY_INSERT(EXPIRIES, &ft->expiries, expiryv[i]); } ft->flows_force_expired += num_to_expire; free(expiryv); /* XXX - this is overcomplicated, perhaps use a separate queue */ } /* Delete all flows that we know about without processing */ static int delete_all_flows(struct FLOWTRACK *ft) { struct FLOW *flow, *nflow; int i; i = 0; for(flow = FLOW_MIN(FLOWS, &ft->flows); flow != NULL; flow = nflow) { nflow = FLOW_NEXT(FLOWS, &ft->flows, flow); FLOW_REMOVE(FLOWS, &ft->flows, flow); EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry); expiry_put(ft, flow->expiry); ft->num_flows--; flow_put(ft, flow); i++; } return (i); } /* * Log our current status. * Includes summary counters and (in verbose mode) the list of current flows * and the tree of expiry events. */ static int statistics(struct FLOWTRACK *ft, FILE *out, pcap_t *pcap) { int i; struct protoent *pe; char proto[32]; struct pcap_stat ps; fprintf(out, "Number of active flows: %d\n", ft->num_flows); fprintf(out, "Packets processed: %llu\n", ft->total_packets); fprintf(out, "Fragments: %llu\n", ft->frag_packets); fprintf(out, "Ignored packets: %llu (%llu non-IP, %llu too short)\n", ft->non_ip_packets + ft->bad_packets, ft->non_ip_packets, ft->bad_packets); fprintf(out, "Flows expired: %llu (%llu forced)\n", ft->flows_expired, ft->flows_force_expired); fprintf(out, "Flows exported: %llu in %llu packets (%llu failures)\n", ft->flows_exported, ft->packets_sent, ft->flows_dropped); if (pcap_stats(pcap, &ps) == 0) { fprintf(out, "Packets received by libpcap: %lu\n", (unsigned long)ps.ps_recv); fprintf(out, "Packets dropped by libpcap: %lu\n", (unsigned long)ps.ps_drop); fprintf(out, "Packets dropped by interface: %lu\n", (unsigned long)ps.ps_ifdrop); } fprintf(out, "\n"); if (ft->flows_expired != 0) { fprintf(out, "Expired flow statistics: minimum average maximum\n"); fprintf(out, " Flow bytes: %12.0f %12.0f %12.0f\n", ft->octets.min, ft->octets.mean, ft->octets.max); fprintf(out, " Flow packets: %12.0f %12.0f %12.0f\n", ft->packets.min, ft->packets.mean, ft->packets.max); fprintf(out, " Duration: %12.2fs %12.2fs %12.2fs\n", ft->duration.min, ft->duration.mean, ft->duration.max); fprintf(out, "\n"); fprintf(out, "Expired flow reasons:\n"); fprintf(out, " tcp = %9llu tcp.rst = %9llu " "tcp.fin = %9llu\n", ft->expired_tcp, ft->expired_tcp_rst, ft->expired_tcp_fin); fprintf(out, " udp = %9llu icmp = %9llu " "general = %9llu\n", ft->expired_udp, ft->expired_icmp, ft->expired_general); fprintf(out, " maxlife = %9llu\n", ft->expired_maxlife); fprintf(out, "over 2 GiB = %9llu\n", ft->expired_overbytes); fprintf(out, " maxflows = %9llu\n", ft->expired_maxflows); fprintf(out, " flushed = %9llu\n", ft->expired_flush); fprintf(out, "\n"); fprintf(out, "Per-protocol statistics: Octets " "Packets Avg Life Max Life\n"); for(i = 0; i < 256; i++) { if (ft->packets_pp[i]) { pe = getprotobynumber(i); snprintf(proto, sizeof(proto), "%s (%d)", pe != NULL ? pe->p_name : "Unknown", i); fprintf(out, " %17s: %14llu %12llu %8.2fs " "%10.2fs\n", proto, ft->octets_pp[i], ft->packets_pp[i], ft->duration_pp[i].mean, ft->duration_pp[i].max); } } } return (0); } static void dump_flows(struct FLOWTRACK *ft, FILE *out) { struct EXPIRY *expiry; time_t now; now = time(NULL); EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) { fprintf(out, "ACTIVE %s\n", format_flow(expiry->flow)); if ((long int) expiry->expires_at - now < 0) { fprintf(out, "EXPIRY EVENT for flow %llu now%s\n", expiry->flow->flow_seq, expiry->expires_at == 0 ? " (FORCED)": ""); } else { fprintf(out, "EXPIRY EVENT for flow %llu in %ld seconds\n", expiry->flow->flow_seq, (long int) expiry->expires_at - now); } fprintf(out, "\n"); } } /* * Figure out how many bytes to skip from front of packet to get past * datalink headers. If pkt is specified, also check whether determine * whether or not it is one that we are interested in (IPv4 or IPv6 for now) * * Returns number of bytes to skip or -1 to indicate that entire * packet should be skipped */ static int datalink_check(int linktype, const u_int8_t *pkt, u_int32_t caplen, int *af) { int i, j; u_int32_t frametype; static const struct DATALINK *dl = NULL; /* Try to cache last used linktype */ if (dl == NULL || dl->dlt != linktype) { for (i = 0; lt[i].dlt != linktype && lt[i].dlt != -1; i++) ; dl = &lt[i]; } if (dl->dlt == -1 || pkt == NULL) return (dl->dlt); if (caplen <= dl->skiplen) return (-1); /* Suck out the frametype */ frametype = 0; if (dl->ft_is_be) { for (j = 0; j < dl->ft_len; j++) { frametype <<= 8; frametype |= pkt[j + dl->ft_off]; } } else { for (j = dl->ft_len - 1; j >= 0 ; j--) { frametype <<= 8; frametype |= pkt[j + dl->ft_off]; } } frametype &= dl->ft_mask; if (frametype == dl->ft_v4) *af = AF_INET; else if (frametype == dl->ft_v6) *af = AF_INET6; else return (-1); return (dl->skiplen); } /* * Per-packet callback function from libpcap. Pass the packet (if it is IP) * sans datalink headers to process_packet. */ static void flow_cb(u_char *user_data, const struct pcap_pkthdr* phdr, const u_char *pkt) { int s, af; struct CB_CTXT *cb_ctxt = (struct CB_CTXT *)user_data; struct timeval tv; s = datalink_check(cb_ctxt->linktype, pkt, phdr->caplen, &af); if (s < 0 || (!cb_ctxt->want_v6 && af == AF_INET6)) { cb_ctxt->ft->non_ip_packets++; } else { tv.tv_sec = phdr->ts.tv_sec; tv.tv_usec = phdr->ts.tv_usec; if (process_packet(cb_ctxt->ft, pkt + s, af, phdr->caplen - s, phdr->len - s, &tv) == PP_MALLOC_FAIL) cb_ctxt->fatal = 1; } } static void print_timeouts(struct FLOWTRACK *ft, FILE *out) { fprintf(out, " TCP timeout: %ds\n", ft->tcp_timeout); fprintf(out, " TCP post-RST timeout: %ds\n", ft->tcp_rst_timeout); fprintf(out, " TCP post-FIN timeout: %ds\n", ft->tcp_fin_timeout); fprintf(out, " UDP timeout: %ds\n", ft->udp_timeout); fprintf(out, " ICMP timeout: %ds\n", ft->icmp_timeout); fprintf(out, " General timeout: %ds\n", ft->general_timeout); fprintf(out, " Maximum lifetime: %ds\n", ft->maximum_lifetime); fprintf(out, " Expiry interval: %ds\n", ft->expiry_interval); } static int accept_control(int lsock, struct NETFLOW_TARGET *target, struct FLOWTRACK *ft, pcap_t *pcap, int *exit_request, int *stop_collection_flag) { unsigned char buf[64], *p; FILE *ctlf; int fd, ret; if ((fd = accept(lsock, NULL, NULL)) == -1) { logit(LOG_ERR, "ctl accept: %s - exiting", strerror(errno)); return(-1); } if ((ctlf = fdopen(fd, "r+")) == NULL) { logit(LOG_ERR, "fdopen: %s - exiting\n", strerror(errno)); close(fd); return (-1); } setlinebuf(ctlf); if (fgets(buf, sizeof(buf), ctlf) == NULL) { logit(LOG_ERR, "Control socket yielded no data"); return (0); } if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; if (verbose_flag) logit(LOG_DEBUG, "Control socket \"%s\"", buf); /* XXX - use dispatch table */ ret = -1; if (strcmp(buf, "help") == 0) { fprintf(ctlf, "Valid control words are:\n"); fprintf(ctlf, "\tdebug+ debug- delete-all dump-flows exit " "expire-all\n"); fprintf(ctlf, "\tshutdown start-gather statistics stop-gather " "timeouts\n"); fprintf(ctlf, "\tsend-template\n"); ret = 0; } else if (strcmp(buf, "shutdown") == 0) { fprintf(ctlf, "softflowd[%u]: Shutting down gracefully...\n", getpid()); graceful_shutdown_request = 1; ret = 1; } else if (strcmp(buf, "exit") == 0) { fprintf(ctlf, "softflowd[%u]: Exiting now...\n", getpid()); *exit_request = 1; ret = 1; } else if (strcmp(buf, "expire-all") == 0) { netflow9_resend_template(); fprintf(ctlf, "softflowd[%u]: Expired %d flows.\n", getpid(), check_expired(ft, target, CE_EXPIRE_ALL)); ret = 0; } else if (strcmp(buf, "send-template") == 0) { netflow9_resend_template(); fprintf(ctlf, "softflowd[%u]: Template will be sent at " "next flow export\n", getpid()); ret = 0; } else if (strcmp(buf, "delete-all") == 0) { fprintf(ctlf, "softflowd[%u]: Deleted %d flows.\n", getpid(), delete_all_flows(ft)); ret = 0; } else if (strcmp(buf, "statistics") == 0) { fprintf(ctlf, "softflowd[%u]: Accumulated statistics " "since %s UTC:\n", getpid(), format_time(ft->system_boot_time.tv_sec)); statistics(ft, ctlf, pcap); ret = 0; } else if (strcmp(buf, "debug+") == 0) { fprintf(ctlf, "softflowd[%u]: Debug level increased.\n", getpid()); verbose_flag = 1; ret = 0; } else if (strcmp(buf, "debug-") == 0) { fprintf(ctlf, "softflowd[%u]: Debug level decreased.\n", getpid()); verbose_flag = 0; ret = 0; } else if (strcmp(buf, "stop-gather") == 0) { fprintf(ctlf, "softflowd[%u]: Data collection stopped.\n", getpid()); *stop_collection_flag = 1; ret = 0; } else if (strcmp(buf, "start-gather") == 0) { fprintf(ctlf, "softflowd[%u]: Data collection resumed.\n", getpid()); *stop_collection_flag = 0; ret = 0; } else if (strcmp(buf, "dump-flows") == 0) { fprintf(ctlf, "softflowd[%u]: Dumping flow data:\n", getpid()); dump_flows(ft, ctlf); ret = 0; } else if (strcmp(buf, "timeouts") == 0) { fprintf(ctlf, "softflowd[%u]: Printing timeouts:\n", getpid()); print_timeouts(ft, ctlf); ret = 0; } else { fprintf(ctlf, "Unknown control commmand \"%s\"\n", buf); ret = 0; } fclose(ctlf); close(fd); return (ret); } static int connsock(struct sockaddr_storage *addr, socklen_t len, int hoplimit) { int s; unsigned int h6; unsigned char h4; struct sockaddr_in *in4 = (struct sockaddr_in *)addr; struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr; if ((s = socket(addr->ss_family, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "socket() error: %s\n", strerror(errno)); exit(1); } if (connect(s, (struct sockaddr*)addr, len) == -1) { fprintf(stderr, "connect() error: %s\n", strerror(errno)); exit(1); } switch (addr->ss_family) { case AF_INET: /* Default to link-local TTL for multicast addresses */ if (hoplimit == -1 && IN_MULTICAST(in4->sin_addr.s_addr)) hoplimit = 1; if (hoplimit == -1) break; h4 = hoplimit; if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &h4, sizeof(h4)) == -1) { fprintf(stderr, "setsockopt(IP_MULTICAST_TTL, " "%u): %s\n", h4, strerror(errno)); exit(1); } break; case AF_INET6: /* Default to link-local hoplimit for multicast addresses */ if (hoplimit == -1 && IN6_IS_ADDR_MULTICAST(&in6->sin6_addr)) hoplimit = 1; if (hoplimit == -1) break; h6 = hoplimit; if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &h6, sizeof(h6)) == -1) { fprintf(stderr, "setsockopt(IPV6_MULTICAST_HOPS, %u): " "%s\n", h6, strerror(errno)); exit(1); } } return(s); } static int unix_listener(const char *path) { struct sockaddr_un addr; socklen_t addrlen; int s; memset(&addr, '\0', sizeof(addr)); addr.sun_family = AF_UNIX; if (strlcpy(addr.sun_path, path, sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) { fprintf(stderr, "control socket path too long\n"); exit(1); } addr.sun_path[sizeof(addr.sun_path) - 1] = '\0'; addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(path) + 1; #ifdef SOCK_HAS_LEN addr.sun_len = addrlen; #endif if ((s = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "unix domain socket() error: %s\n", strerror(errno)); exit(1); } unlink(path); if (bind(s, (struct sockaddr*)&addr, addrlen) == -1) { fprintf(stderr, "unix domain bind(\"%s\") error: %s\n", addr.sun_path, strerror(errno)); exit(1); } if (listen(s, 64) == -1) { fprintf(stderr, "unix domain listen() error: %s\n", strerror(errno)); exit(1); } return (s); } static void setup_packet_capture(struct pcap **pcap, int *linktype, char *dev, char *capfile, char *bpf_prog, int need_v6) { char ebuf[PCAP_ERRBUF_SIZE]; struct bpf_program prog_c; u_int32_t bpf_mask, bpf_net; /* Open pcap */ if (dev != NULL) { if ((*pcap = pcap_open_live(dev, need_v6 ? LIBPCAP_SNAPLEN_V6 : LIBPCAP_SNAPLEN_V4, 1, 0, ebuf)) == NULL) { fprintf(stderr, "pcap_open_live: %s\n", ebuf); exit(1); } if (pcap_lookupnet(dev, &bpf_net, &bpf_mask, ebuf) == -1) bpf_net = bpf_mask = 0; } else { if ((*pcap = pcap_open_offline(capfile, ebuf)) == NULL) { fprintf(stderr, "pcap_open_offline(%s): %s\n", capfile, ebuf); exit(1); } bpf_net = bpf_mask = 0; } *linktype = pcap_datalink(*pcap); if (datalink_check(*linktype, NULL, 0, NULL) == -1) { fprintf(stderr, "Unsupported datalink type %d\n", *linktype); exit(1); } /* Attach BPF filter, if specified */ if (bpf_prog != NULL) { if (pcap_compile(*pcap, &prog_c, bpf_prog, 1, bpf_mask) == -1) { fprintf(stderr, "pcap_compile(\"%s\"): %s\n", bpf_prog, pcap_geterr(*pcap)); exit(1); } if (pcap_setfilter(*pcap, &prog_c) == -1) { fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(*pcap)); exit(1); } } #ifdef BIOCLOCK /* * If we are reading from an device (not a file), then * lock the underlying BPF device to prevent changes in the * unprivileged child */ if (dev != NULL && ioctl(pcap_fileno(*pcap), BIOCLOCK) < 0) { fprintf(stderr, "ioctl(BIOCLOCK) failed: %s\n", strerror(errno)); exit(1); } #endif } static void init_flowtrack(struct FLOWTRACK *ft) { /* Set up flow-tracking structure */ memset(ft, '\0', sizeof(*ft)); ft->next_flow_seq = 1; FLOW_INIT(&ft->flows); EXPIRY_INIT(&ft->expiries); freelist_init(&ft->flow_freelist, sizeof(struct FLOW)); freelist_init(&ft->expiry_freelist, sizeof(struct EXPIRY)); ft->max_flows = DEFAULT_MAX_FLOWS; ft->track_level = TRACK_FULL; ft->tcp_timeout = DEFAULT_TCP_TIMEOUT; ft->tcp_rst_timeout = DEFAULT_TCP_RST_TIMEOUT; ft->tcp_fin_timeout = DEFAULT_TCP_FIN_TIMEOUT; ft->udp_timeout = DEFAULT_UDP_TIMEOUT; ft->icmp_timeout = DEFAULT_ICMP_TIMEOUT; ft->general_timeout = DEFAULT_GENERAL_TIMEOUT; ft->maximum_lifetime = DEFAULT_MAXIMUM_LIFETIME; ft->expiry_interval = DEFAULT_EXPIRY_INTERVAL; } static char * argv_join(int argc, char **argv) { int i; size_t ret_len; char *ret; ret_len = 0; ret = NULL; for (i = 0; i < argc; i++) { ret_len += strlen(argv[i]); if ((ret = realloc(ret, ret_len + 2)) == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(1); } if (i == 0) ret[0] = '\0'; else { ret_len++; /* Make room for ' ' */ strlcat(ret, " ", ret_len + 1); } strlcat(ret, argv[i], ret_len + 1); } return (ret); } /* Display commandline usage information */ static void usage(void) { fprintf(stderr, "Usage: %s [options] [bpf_program]\n" "This is %s version %s. Valid commandline options:\n" " -i [idx:]interface Specify interface to listen on\n" " -r pcap_file Specify packet capture file to read\n" " -t timeout=time Specify named timeout\n" " -m max_flows Specify maximum number of flows to track (default %d)\n" " -n host:port Send Cisco NetFlow(tm)-compatible packets to host:port\n" " -p pidfile Record pid in specified file\n" " (default: %s)\n" " -c pidfile Location of control socket\n" " (default: %s)\n" " -v 1|5|9 NetFlow export packet version\n" " -L hoplimit Set TTL/hoplimit for export datagrams\n" " -T full|proto|ip Set flow tracking level (default: full)\n" " -6 Track IPv6 flows, regardless of whether selected \n" " NetFlow export protocol supports it\n" " -d Don't daemonise (run in foreground)\n" " -D Debug mode: foreground + verbosity + track v6 flows\n" " -h Display this help\n" "\n" "Valid timeout names and default values:\n" " tcp (default %6d)" " tcp.rst (default %6d)" " tcp.fin (default %6d)\n" " udp (default %6d)" " icmp (default %6d)" " general (default %6d)\n" " maxlife (default %6d)" " expint (default %6d)\n" "\n" , PROGNAME, PROGNAME, PROGVER, DEFAULT_MAX_FLOWS, DEFAULT_PIDFILE, DEFAULT_CTLSOCK, DEFAULT_TCP_TIMEOUT, DEFAULT_TCP_RST_TIMEOUT, DEFAULT_TCP_FIN_TIMEOUT, DEFAULT_UDP_TIMEOUT, DEFAULT_ICMP_TIMEOUT, DEFAULT_GENERAL_TIMEOUT, DEFAULT_MAXIMUM_LIFETIME, DEFAULT_EXPIRY_INTERVAL); } static void set_timeout(struct FLOWTRACK *ft, const char *to_spec) { char *name, *value; int timeout; if ((name = strdup(to_spec)) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } if ((value = strchr(name, '=')) == NULL || *(++value) == '\0') { fprintf(stderr, "Invalid -t option \"%s\".\n", name); usage(); exit(1); } *(value - 1) = '\0'; timeout = convtime(value); if (timeout < 0) { fprintf(stderr, "Invalid -t timeout.\n"); usage(); exit(1); } if (strcmp(name, "tcp") == 0) ft->tcp_timeout = timeout; else if (strcmp(name, "tcp.rst") == 0) ft->tcp_rst_timeout = timeout; else if (strcmp(name, "tcp.fin") == 0) ft->tcp_fin_timeout = timeout; else if (strcmp(name, "udp") == 0) ft->udp_timeout = timeout; else if (strcmp(name, "icmp") == 0) ft->icmp_timeout = timeout; else if (strcmp(name, "general") == 0) ft->general_timeout = timeout; else if (strcmp(name, "maxlife") == 0) ft->maximum_lifetime = timeout; else if (strcmp(name, "expint") == 0) ft->expiry_interval = timeout; else { fprintf(stderr, "Invalid -t name.\n"); usage(); exit(1); } if (ft->general_timeout == 0) { fprintf(stderr, "\"general\" flow timeout must be " "greater than zero\n"); exit(1); } free(name); } static void parse_hostport(const char *s, struct sockaddr *addr, socklen_t *len) { char *orig, *host, *port; struct addrinfo hints, *res; int herr; if ((host = orig = strdup(s)) == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } if ((port = strrchr(host, ':')) == NULL || *(++port) == '\0' || *host == '\0') { fprintf(stderr, "Invalid -n argument.\n"); usage(); exit(1); } *(port - 1) = '\0'; /* Accept [host]:port for numeric IPv6 addresses */ if (*host == '[' && *(port - 2) == ']') { host++; *(port - 2) = '\0'; } memset(&hints, '\0', sizeof(hints)); hints.ai_socktype = SOCK_DGRAM; if ((herr = getaddrinfo(host, port, &hints, &res)) == -1) { fprintf(stderr, "Address lookup failed: %s\n", gai_strerror(herr)); exit(1); } if (res == NULL || res->ai_addr == NULL) { fprintf(stderr, "No addresses found for [%s]:%s\n", host, port); exit(1); } if (res->ai_addrlen > *len) { fprintf(stderr, "Address too long\n"); exit(1); } memcpy(addr, res->ai_addr, res->ai_addrlen); free(orig); *len = res->ai_addrlen; } /* * Drop privileges and chroot, will exit on failure */ static void drop_privs(void) { struct passwd *pw; if ((pw = getpwnam(PRIVDROP_USER)) == NULL) { logit(LOG_ERR, "Unable to find unprivileged user \"%s\"", PRIVDROP_USER); exit(1); } if (chdir(PRIVDROP_CHROOT_DIR) != 0) { logit(LOG_ERR, "Unable to chdir to chroot directory \"%s\": %s", PRIVDROP_CHROOT_DIR, strerror(errno)); exit(1); } if (chroot(PRIVDROP_CHROOT_DIR) != 0) { logit(LOG_ERR, "Unable to chroot to directory \"%s\": %s", PRIVDROP_CHROOT_DIR, strerror(errno)); exit(1); } if (chdir("/") != 0) { logit(LOG_ERR, "Unable to chdir to chroot root: %s", strerror(errno)); exit(1); } if (setgroups(1, &pw->pw_gid) != 0) { logit(LOG_ERR, "Couldn't setgroups (%u): %s", (unsigned int)pw->pw_gid, strerror(errno)); exit(1); } #if defined(HAVE_SETRESGID) if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) { #elif defined(HAVE_SETREGID) if (setregid(pw->pw_gid, pw->pw_gid) == -1) { #else if (setegid(pw->pw_gid) == -1 || setgid(pw->pw_gid) == -1) { #endif logit(LOG_ERR, "Couldn't set gid (%u): %s", (unsigned int)pw->pw_gid, strerror(errno)); exit(1); } #if defined(HAVE_SETRESUID) if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) { #elif defined(HAVE_SETREUID) if (setreuid(pw->pw_uid, pw->pw_uid) == -1) { #else if (seteuid(pw->pw_uid) == -1 || setuid(pw->pw_uid) == -1) { #endif logit(LOG_ERR, "Couldn't set uid (%u): %s", (unsigned int)pw->pw_uid, strerror(errno)); exit(1); } } int main(int argc, char **argv) { char *dev, *capfile, *bpf_prog, dest_addr[256], dest_serv[256]; const char *pidfile_path, *ctlsock_path; extern char *optarg; extern int optind; int ch, dontfork_flag, linktype, ctlsock, i, err, always_v6, r; int stop_collection_flag, exit_request, hoplimit; pcap_t *pcap = NULL; struct sockaddr_storage dest; struct FLOWTRACK flowtrack; socklen_t dest_len; struct NETFLOW_TARGET target; struct CB_CTXT cb_ctxt; struct pollfd pl[2]; closefrom(STDERR_FILENO + 1); init_flowtrack(&flowtrack); memset(&dest, '\0', sizeof(dest)); dest_len = 0; memset(&target, '\0', sizeof(target)); target.fd = -1; target.dialect = &nf[0]; hoplimit = -1; bpf_prog = NULL; ctlsock = -1; dev = capfile = NULL; pidfile_path = DEFAULT_PIDFILE; ctlsock_path = DEFAULT_CTLSOCK; dontfork_flag = 0; always_v6 = 0; while ((ch = getopt(argc, argv, "6hdDL:T:i:r:f:t:n:m:p:c:v:")) != -1) { switch (ch) { case '6': always_v6 = 1; break; case 'h': usage(); return (0); case 'D': verbose_flag = 1; always_v6 = 1; /* FALLTHROUGH */ case 'd': dontfork_flag = 1; break; case 'i': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already " "specified.\n\n"); usage(); exit(1); } dev = strsep(&optarg, ":"); if (optarg != NULL) { if_index = (u_int16_t) atoi(dev); dev = optarg; } if (verbose_flag) fprintf(stderr, "Using %s (idx: %d)\n", dev, if_index); break; case 'r': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already " "specified.\n\n"); usage(); exit(1); } capfile = optarg; dontfork_flag = 1; ctlsock_path = NULL; break; case 't': /* Will exit on failure */ set_timeout(&flowtrack, optarg); break; case 'T': if (strcasecmp(optarg, "full") == 0) flowtrack.track_level = TRACK_FULL; else if (strcasecmp(optarg, "proto") == 0) flowtrack.track_level = TRACK_IP_PROTO; else if (strcasecmp(optarg, "ip") == 0) flowtrack.track_level = TRACK_IP_ONLY; else { fprintf(stderr, "Unknown flow tracking " "level\n"); usage(); exit(1); } break; case 'L': hoplimit = atoi(optarg); if (hoplimit < 0 || hoplimit > 255) { fprintf(stderr, "Invalid hop limit\n\n"); usage(); exit(1); } break; case 'm': if ((flowtrack.max_flows = atoi(optarg)) < 0) { fprintf(stderr, "Invalid maximum flows\n\n"); usage(); exit(1); } break; case 'n': /* Will exit on failure */ dest_len = sizeof(dest); parse_hostport(optarg, (struct sockaddr *)&dest, &dest_len); break; case 'p': pidfile_path = optarg; break; case 'c': if (strcmp(optarg, "none") == 0) ctlsock_path = NULL; else ctlsock_path = optarg; break; case 'v': for(i = 0, r = atoi(optarg); nf[i].version != -1; i++) { if (nf[i].version == r) break; } if (nf[i].version == -1) { fprintf(stderr, "Invalid NetFlow version\n"); exit(1); } target.dialect = &nf[i]; break; default: fprintf(stderr, "Invalid commandline option.\n"); usage(); exit(1); } } if (capfile == NULL && dev == NULL) { fprintf(stderr, "-i or -r option not specified.\n"); usage(); exit(1); } /* join remaining arguments (if any) into bpf program */ bpf_prog = argv_join(argc - optind, argv + optind); /* Will exit on failure */ setup_packet_capture(&pcap, &linktype, dev, capfile, bpf_prog, target.dialect->v6_capable || always_v6); /* Netflow send socket */ if (dest.ss_family != 0) { if ((err = getnameinfo((struct sockaddr *)&dest, dest_len, dest_addr, sizeof(dest_addr), dest_serv, sizeof(dest_serv), NI_NUMERICHOST)) == -1) { fprintf(stderr, "getnameinfo: %d\n", err); exit(1); } target.fd = connsock(&dest, dest_len, hoplimit); } /* Control socket */ if (ctlsock_path != NULL) ctlsock = unix_listener(ctlsock_path); /* Will exit on fail */ if (dontfork_flag) { loginit(PROGNAME, 1); } else { FILE *pidfile; daemon(0, 0); loginit(PROGNAME, 0); if ((pidfile = fopen(pidfile_path, "w")) == NULL) { fprintf(stderr, "Couldn't open pidfile %s: %s\n", pidfile_path, strerror(errno)); exit(1); } fprintf(pidfile, "%u\n", getpid()); fclose(pidfile); signal(SIGINT, sighand_graceful_shutdown); signal(SIGTERM, sighand_graceful_shutdown); signal(SIGSEGV, sighand_other); setprotoent(1); drop_privs(); } logit(LOG_NOTICE, "%s v%s starting data collection", PROGNAME, PROGVER); if (dest.ss_family != 0) { logit(LOG_NOTICE, "Exporting flows to [%s]:%s", dest_addr, dest_serv); } /* Main processing loop */ gettimeofday(&flowtrack.system_boot_time, NULL); stop_collection_flag = 0; memset(&cb_ctxt, '\0', sizeof(cb_ctxt)); cb_ctxt.ft = &flowtrack; cb_ctxt.linktype = linktype; cb_ctxt.want_v6 = target.dialect->v6_capable || always_v6; for (r = 0; graceful_shutdown_request == 0; r = 0) { /* * Silly libpcap's timeout function doesn't work, so we * do it here (only if we are reading live) */ if (capfile == NULL) { memset(pl, '\0', sizeof(pl)); /* This can only be set via the control socket */ if (!stop_collection_flag) { pl[0].events = POLLIN|POLLERR|POLLHUP; pl[0].fd = pcap_fileno(pcap); } if (ctlsock != -1) { pl[1].fd = ctlsock; pl[1].events = POLLIN|POLLERR|POLLHUP; } r = poll(pl, (ctlsock == -1) ? 1 : 2, next_expire(&flowtrack)); if (r == -1 && errno != EINTR) { logit(LOG_ERR, "Exiting on poll: %s", strerror(errno)); break; } } /* Accept connection on control socket if present */ if (ctlsock != -1 && pl[1].revents != 0) { if (accept_control(ctlsock, &target, &flowtrack, pcap, &exit_request, &stop_collection_flag) != 0) break; } /* If we have data, run it through libpcap */ if (!stop_collection_flag && (capfile != NULL || pl[0].revents != 0)) { r = pcap_dispatch(pcap, flowtrack.max_flows, flow_cb, (void*)&cb_ctxt); if (r == -1) { logit(LOG_ERR, "Exiting on pcap_dispatch: %s", pcap_geterr(pcap)); break; } else if (r == 0) { logit(LOG_NOTICE, "Shutting down after " "pcap EOF"); graceful_shutdown_request = 1; break; } } r = 0; /* Fatal error from per-packet functions */ if (cb_ctxt.fatal) { logit(LOG_WARNING, "Fatal error - exiting immediately"); break; } /* * Expiry processing happens every recheck_rate seconds * or whenever we have exceeded the maximum number of active * flows */ if (flowtrack.num_flows > flowtrack.max_flows || next_expire(&flowtrack) == 0) { expiry_check: /* * If we are reading from a capture file, we never * expire flows based on time - instead we only * expire flows when the flow table is full. */ if (check_expired(&flowtrack, &target, capfile == NULL ? CE_EXPIRE_NORMAL : CE_EXPIRE_FORCED) < 0) logit(LOG_WARNING, "Unable to export flows"); /* * If we are over max_flows, force-expire the oldest * out first and immediately reprocess to evict them */ if (flowtrack.num_flows > flowtrack.max_flows) { force_expire(&flowtrack, flowtrack.num_flows - flowtrack.max_flows); goto expiry_check; } } } /* Flags set by signal handlers or control socket */ if (graceful_shutdown_request) { logit(LOG_WARNING, "Shutting down on user request"); check_expired(&flowtrack, &target, CE_EXPIRE_ALL); } else if (exit_request) logit(LOG_WARNING, "Exiting immediately on user request"); else logit(LOG_ERR, "Exiting immediately on internal error"); if (capfile != NULL && dontfork_flag) statistics(&flowtrack, stdout, pcap); pcap_close(pcap); if (target.fd != -1) close(target.fd); unlink(pidfile_path); if (ctlsock_path != NULL) unlink(ctlsock_path); return(r == 0 ? 0 : 1); }
08beeumerk-flow
softflowd.c
C
bsd
54,302
#! /bin/sh # mkinstalldirs --- make directory hierarchy # Author: Noah Friedman <friedman@prep.ai.mit.edu> # Created: 1993-05-16 # Public domain # $Id$ errstatus=0 for file do set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'` shift pathcomp= for d do pathcomp="$pathcomp$d" case "$pathcomp" in -* ) pathcomp=./$pathcomp ;; esac if test ! -d "$pathcomp"; then echo "mkdir $pathcomp" mkdir "$pathcomp" || lasterr=$? if test ! -d "$pathcomp"; then errstatus=$lasterr fi fi pathcomp="$pathcomp/" done done exit $errstatus # mkinstalldirs ends here
08beeumerk-flow
mkinstalldirs
Shell
bsd
641
/* * Copyright (c) 2004 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_CLOSEFROM #include <sys/types.h> #include <sys/param.h> #include <unistd.h> #include <stdio.h> #include <limits.h> #include <stdlib.h> #include <stddef.h> #ifdef HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # ifdef HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # ifdef HAVE_SYS_DIR_H # include <sys/dir.h> # endif # ifdef HAVE_NDIR_H # include <ndir.h> # endif #endif #ifndef OPEN_MAX # define OPEN_MAX 256 #endif RCSID("$Id$"); #ifndef lint static const char rcsid[] = "$Sudo: closefrom.c,v 1.6 2004/06/01 20:51:56 millert Exp $"; #endif /* lint */ /* * Close all file descriptors greater than or equal to lowfd. */ void closefrom(int lowfd) { long fd, maxfd; #if defined(HAVE_DIRFD) && defined(HAVE_PROC_PID) char fdpath[PATH_MAX], *endp; struct dirent *dent; DIR *dirp; int len; /* Check for a /proc/$$/fd directory. */ len = snprintf(fdpath, sizeof(fdpath), "/proc/%ld/fd", (long)getpid()); if (len != -1 && len <= sizeof(fdpath) && (dirp = opendir(fdpath))) { while ((dent = readdir(dirp)) != NULL) { fd = strtol(dent->d_name, &endp, 10); if (dent->d_name != endp && *endp == '\0' && fd >= 0 && fd < INT_MAX && fd >= lowfd && fd != dirfd(dirp)) (void) close((int) fd); } (void) closedir(dirp); } else #endif { /* * Fall back on sysconf() or getdtablesize(). We avoid checking * resource limits since it is possible to open a file descriptor * and then drop the rlimit such that it is below the open fd. */ #ifdef HAVE_SYSCONF maxfd = sysconf(_SC_OPEN_MAX); #else maxfd = getdtablesize(); #endif /* HAVE_SYSCONF */ if (maxfd < 0) maxfd = OPEN_MAX; for (fd = lowfd; fd < maxfd; fd++) (void) close((int) fd); } } #endif /* HAVE_CLOSEFROM */
08beeumerk-flow
closefrom.c
C
bsd
2,690
/* OPENBSD ORIGINAL: lib/libc/string/strlcpy.c */ /* $OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "common.h" #ifndef HAVE_STRLCPY RCSID("$Id$"); #if defined(LIBC_SCCS) && !defined(lint) static char *rcsid = "$OpenBSD: strlcpy.c,v 1.8 2003/06/17 21:56:24 millert Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <string.h> /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ size_t strlcpy(char *dst, const char *src, size_t siz) { register char *d = dst; register const char *s = src; register size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } #endif /* !HAVE_STRLCPY */
08beeumerk-flow
strlcpy.c
C
bsd
1,900
#!/bin/bash # # softflowd Starts softflowd NetFlow probe # $Id$ # # chkconfig: 2345 95 02 # description: Starts and stops the softflowd Netflow probe # Source function library. . /etc/init.d/functions SOFTFLOW_CONF=/etc/sysconfig/softflowd SOFTFLOW_LOCK=/var/lock/subsys/softflowd SOFTFLOW_PROG=/usr/sbin/softflowd SOFTFLOW_OPTS="-i eth0" # Source config if [ -f $SOFTFLOW_CONF ]; then . $SOFTFLOW_CONF fi [ -x $SOFTFLOW_PROG ] || exit 0 RETVAL=0 start() { echo -n $"Starting softflowd: " daemon $SOFTFLOW_PROG $SOFTFLOW_OPTS RETVAL=$? echo [ $RETVAL -eq 0 ] && touch $SOFTFLOW_LOCK return $RETVAL } stop() { echo -n $"Shutting down softflowd: " killproc $SOFTFLOW_PROG RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f $SOFTFLOW_LOCK return $RETVAL } restart() { stop start } case "$1" in start) start ;; stop) stop ;; status) status $SOFTFLOW_PROG ;; restart|reload) restart ;; condrestart) [ -f $SOFTFLOW_LOCK ] && restart || : ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart}" exit 1 esac exit $?
08beeumerk-flow
softflowd.init
Shell
bsd
1,111
/* * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id$ */ /* Select our tree types for various data structures */ #if defined(FLOW_RB) #define FLOW_HEAD RB_HEAD #define FLOW_ENTRY RB_ENTRY #define FLOW_PROTOTYPE RB_PROTOTYPE #define FLOW_GENERATE RB_GENERATE #define FLOW_INSERT RB_INSERT #define FLOW_FIND RB_FIND #define FLOW_REMOVE RB_REMOVE #define FLOW_FOREACH RB_FOREACH #define FLOW_MIN RB_MIN #define FLOW_NEXT RB_NEXT #define FLOW_INIT RB_INIT #elif defined(FLOW_SPLAY) #define FLOW_HEAD SPLAY_HEAD #define FLOW_ENTRY SPLAY_ENTRY #define FLOW_PROTOTYPE SPLAY_PROTOTYPE #define FLOW_GENERATE SPLAY_GENERATE #define FLOW_INSERT SPLAY_INSERT #define FLOW_FIND SPLAY_FIND #define FLOW_REMOVE SPLAY_REMOVE #define FLOW_FOREACH SPLAY_FOREACH #define FLOW_MIN SPLAY_MIN #define FLOW_NEXT SPLAY_NEXT #define FLOW_INIT SPLAY_INIT #else #error No flow tree type defined #endif #if defined(EXPIRY_RB) #define EXPIRY_HEAD RB_HEAD #define EXPIRY_ENTRY RB_ENTRY #define EXPIRY_PROTOTYPE RB_PROTOTYPE #define EXPIRY_GENERATE RB_GENERATE #define EXPIRY_INSERT RB_INSERT #define EXPIRY_FIND RB_FIND #define EXPIRY_REMOVE RB_REMOVE #define EXPIRY_FOREACH RB_FOREACH #define EXPIRY_MIN RB_MIN #define EXPIRY_NEXT RB_NEXT #define EXPIRY_INIT RB_INIT #elif defined(EXPIRY_SPLAY) #define EXPIRY_HEAD SPLAY_HEAD #define EXPIRY_ENTRY SPLAY_ENTRY #define EXPIRY_PROTOTYPE SPLAY_PROTOTYPE #define EXPIRY_GENERATE SPLAY_GENERATE #define EXPIRY_INSERT SPLAY_INSERT #define EXPIRY_FIND SPLAY_FIND #define EXPIRY_REMOVE SPLAY_REMOVE #define EXPIRY_FOREACH SPLAY_FOREACH #define EXPIRY_MIN SPLAY_MIN #define EXPIRY_NEXT SPLAY_NEXT #define EXPIRY_INIT SPLAY_INIT #else #error No expiry tree type defined #endif
08beeumerk-flow
treetype.h
C
bsd
2,977
.\" $Id$ .\" .\" Copyright (c) 2002 Damien Miller. All rights reserved. .\" Portions Copyright (c) 2001 Kevin Steves. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. .\" .Dd October 14, 2002 .Dt SOFTFLOWD 8 .Os .Sh NAME .Nm softflowd .Nd Traffic flow monitoring .Sh SYNOPSIS .Nm softflowd .Op Fl 6dDh .Op Fl L Ar hoplimit .Op Fl T Ar track_level .Op Fl c Ar ctl_sock .Ek .Oo Fl i\ \& .Sm off .Oo Ar if_ndx : Oc .Ar interface .Sm on .Oc .Bk words .Op Fl m Ar max_flows .Op Fl n Ar host:port .Op Fl p Ar pidfile .Op Fl r Ar pcap_file .Op Fl t Ar timeout_name=seconds .Op Fl v Ar netflow_version .Op bpf_expression .Sh DESCRIPTION .Nm is a software implementation of a flow-based network traffic monitor. .Nm reads network traffic and gathers information about active traffic flows. A "traffic flow" is communication between two IP addresses or (if the overlying protocol is TCP or UDP) address/port tuples. .Pp The intended use of .Nm is as a software implementation of Cisco's NetFlow(tm) traffic account system. .Nm supports data export using versions 1, 5 or 9 of the NetFlow protocol. .Nm can also run in statistics-only mode, where it just collects summary information. However, too few statistics are collected to make this mode really useful for anything other than debugging. .Pp Network traffic may be obtained by listening on a promiscuous network interface or by reading stored .Xr pcap 3 files, such as those written by .Xr tcpdump 8 . Traffic may be filtered with an optional .Xr bpf 4 program, specified on the command-line as .Ar bpf_expression . .Nm is IPv6 capable and will track IPv6 flows if the NetFlow export protocol supports it (currently only NetFlow v.9 possesses an IPv6 export capability). .Pp .Nm tries to track only active traffic flows. When the flow has been quiescent for a period of time it is expired automatically. Flows may also be expired early if they approach their traffic counts exceed 2 Gib or if the number of flows being tracked exceeds .Ar max_flows (default: 8192). In this last case, flows are expired oldest-first. .Pp Upon expiry, the flow information is accumulated into statistics which may be viewed using .Xr softflowctl 8 . If the .Fl n option has been specified the flow information is formatted in a UDP datagram which is compatible with versions 1, 5 or 9 of Cisco's NetFlow(tm) accounting export format. These records are sent to the specified .Ar host and .Ar port . The host may represent a unicast host or a multicast group. .Pp The command-line options are as follows: .Bl -tag -width Ds .It Fl n Ar host:port Specify the .Ar host and .Ar port that the accounting datagrams are to be sent to. The host may be specified using a hostname or using a numeric IPv4 or IPv6 address. Numeric IPv6 addresses should be encosed in square brackets to avoid ambiguity between the address and the port. The destination port may be a portname listed in .Xr services 5 or a numeric port. .It Fl i Xo .Sm off .Oo Ar if_ndx : Oc .Ar interface .Sm on .Xc Specify a network interface on which to listen for traffic. Either the .Fl i or the .Fl r options must be specified. .It Fl r Ar pcap_file Specify that .Nm should read from a .Xr pcap 3 packet capture file (such as one created with the .Fl w option of .Xr tcpdump 8 ) file rather than a network interface. .Nm processes the whole capture file and only expires flows when .Ar max_flows is exceeded. In this mode, .Nm will not fork and will automatically print summary statistics before exiting. .It Fl p Ar pidfile Specify an alternate location to store the process ID when in daemon mode. Default is .Pa /var/run/softflowd.pid .It Fl c Ar ctlsock Specify an alternate location for the remote control socket in daemon mode. Default is .Pa /var/run/softflowd.ctl .It Fl m Ar max_flows Specify the maximum number of flow to concurrently track. If this limit is exceeded, the flows which have least recently seen traffic are forcibly expired. In practice, the actual maximum may briefly exceed this limit by a small amount as expiry processing happens less frequently than traffic collection. The default is 8192 flows, which corresponds to slightly less than 800k of working data. .It Fl t Ar timeout_name=time Set the timeout names .Ar timeout_name to .Ar time Refer to the .Sx Timeouts section for the valid timeout names and their meanings. The .Ar time parameter may be specified using one of the formats explained in the .Sx Time Formats section below. .It Fl d Specify that .Nm should not fork and daemonise itself. .It Fl 6 Force .Nm To track IPv6 flows even if the NetFlow export protocol does not support reporting them. This is useful for debugging and statistics gathering only. .It Fl D Places .Nm in a debugging mode. This implies the .Fl d and .Fl 6 flags and turns on additional debugging output. .It Fl h Display command-line usage information. .It Fl L Ar hoplimit Set the IPv4 TTL or the IPv6 hop limit to .Ar hoplimit . .Nm will use the default system TTL when exporting flows to a unicast host. When exporting to a multicast group, the default TTL will be 1 (i.e. link-local). .It Fl T Ar track_level Specify which flow elements .Nm should be used to define a flow. .Ar track_level may be one of: .Dq full (track everything in the flow, the default), .Dq proto (track source and destination addresses and protocol), or .Dq ip (only track source and destination addresses). Selecting either of the latter options will produce flows with less information in them (e.g. TCP/UDP ports will not be recorded). This will cause flows to be consolidated, reducing the quantity of output and CPU load that .Nm will place on the system at the cost of some detail being lost. .It Fl v Ar netflow_version Specify which version of the NetFlow(tm) protocol .Nm should use for export of the flow data. Supported versions are 1, 5 and 9. Default is version 5. .El .Pp Any further command-line arguments will be concatenated together and applied as a .Xr bpf 4 packet filter. This filter will cause .Nm to ignore the specified traffic. .Ss Timeouts .Pp .Nm will expire quiescent flows after user-configurable periods. The exact timeout used depends on the nature of the flow. The various timeouts that may be set from the command-line (using the .Fl t option) and their meanings are: .Bl -tag -width Ds .It Ar general This is the general timeout applied to all traffic unless overridden by one of the other timeouts. .It Ar tcp This is the general TCP timeout, applied to open TCP connections. .It Ar tcp.rst This timeout is applied to a TCP connection when a RST packet has been sent by one or both endpoints. .It Ar tcp.fin This timeout is applied to a TCP connection when a FIN packet has been sent by both endpoints. .It Ar udp This is the general UDP timeout, applied to all UDP connections. .It Ar maxlife This is the maximum lifetime that a flow may exist for. All flows are forcibly expired when they pass .Ar maxlife seconds. To disable this feature, specify a .Ar maxlife of 0. .It Ar expint Specify the interval between expiry checks. Increase this to group more flows into a NetFlow packet. To disable this feature, specify a .Ar expint of 0. .El .Pp Flows may also be expired if there are not enough flow entries to hold them or if their traffic exceeds 2 Gib in either direction. .Xr softflowctl 8 may be used to print information on the average lifetimes of flows and the reasons for their expiry. .Ss Time Formats .Pp .Nm command-line arguments that specify time may be expressed using a sequence of the form: .Sm off .Ar time Op Ar qualifier , .Sm on where .Ar time is a positive integer value and .Ar qualifier is one of the following: .Pp .Bl -tag -width Ds -compact -offset indent .It Cm <none> seconds .It Cm s | Cm S seconds .It Cm m | Cm M minutes .It Cm h | Cm H hours .It Cm d | Cm D days .It Cm w | Cm W weeks .El .Pp Each member of the sequence is added together to calculate the total time value. .Pp Time format examples: .Pp .Bl -tag -width Ds -compact -offset indent .It 600 600 seconds (10 minutes) .It 10m 10 minutes .It 1h30m 1 hour 30 minutes (90 minutes) .El .Ss Run-time Control .Pp A daemonised .Nm instance may be controlled using the .Xr softflowctl 8 command. This interface allows one to shut down the daemon, force expiry of all tracked flows and extract debugging and summary data. Also, upon receipt of a .Dv SIGTERM or .DV SIGINT .Nm will cause .Nm to exit, after expiring all flows (and thus sending flow export packets if .Fl n was specified on the command-line). If you do not want to export flows upon shutdown, clear them first with .Xr softflowctl 8 or use .Xr softflowctl 8 's .Dq exit command. .Sh EXAMPLES .Bl -tag -width Ds .It softflowd -i fxp0 This command-line will cause .Nm to listen on interface fxp0 and to run in statistics gathering mode only (i.e. no NetFlow data export). .It softflowd -i fxp0 -n 10.1.0.2:4432 This command-line will cause .Nm to listen on interface fxp0 and to export NetFlow v.5 datagrams on flow expiry to a flow collector running on 10.1.0.2 port 4432. .It softflowd -v 5 -i fxp0 -n 10.1.0.2:4432 -m 65536 -t udp=1m30s This command-line increases the number of concurrent flows that .Nm will track to 65536 and increases the timeout for UDP flows to 90 seconds. .It softflowd -v 9 -i fxp0 -n 224.0.1.20:4432 -L 64 This command-line will export NetFlow v.9 flows to the multicast group 224.0.1.20. The export datagrams will have their TTL set to 64, so multicast receivers can be many hops away. .It softflowd -i fxp0 -p /var/run/sfd.pid.fxp0 -c /var/run/sfd.ctl.fxp0 This command-line specifies alternate locations for the control socket and pid file. Similar command-lines are useful when running multiple instances of .Nm on a single machine. .El .Sh FILES .Bl -tag -width Ds .It Pa /var/run/softflowd.pid This file stores the process ID when .Nm is in daemon mode. This location may be overridden using the .Fl p command-line option. .It Pa /var/run/softflowd.ctl This is the remote control socket. .Nm listens on this socket for commands from .Xr softflowctl 8 . This location may be overridden using the .Fl c command-line option. .El .Sh BUGS Currently .Nm does not handle maliciously fragmented packets properly, i.e. packets fragemented such that the UDP or TCP header does not fit into the first fragment. It will product correct traffic counts when presented with maliciously fragmented packets, but will not record TCP or UDP port information. .Sh AUTHORS .An Damien Miller Aq djm@mindrot.org .Sh SEE ALSO .Xr softflowctl 8 , .Xr tcpdump 8 , .Xr pcap 3 , .Xr bpf 4 .Bd -literal http://www.cisco.com/univercd/cc/td/doc/product/rtrmgmt/nfc/nfc_3_0/nfc_ug/nfcform.htm .Ed
08beeumerk-flow
softflowd.8
Roff Manpage
bsd
11,910
/* OPENBSD ORIGINAL: lib/libc/gen/daemon.c */ /*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" #ifndef HAVE_DAEMON #if defined(LIBC_SCCS) && !defined(lint) static char rcsid[] = "$OpenBSD: daemon.c,v 1.5 2003/07/15 17:32:41 deraadt Exp $"; #endif /* LIBC_SCCS and not lint */ int daemon(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return (-1); case 0: #ifdef HAVE_CYGWIN register_9x_service(); #endif break; default: #ifdef HAVE_CYGWIN /* * This sleep avoids a race condition which kills the * child process if parent is started by a NT/W2K service. */ sleep(1); #endif _exit(0); } if (setsid() == -1) return (-1); if (!nochdir) (void)chdir("/"); if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if (fd > 2) (void)close (fd); } return (0); } #endif /* !HAVE_DAEMON */
08beeumerk-flow
daemon.c
C
bsd
2,517
/* * Copyright (c) 2002 Damien Miller. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SOFTFLOWD_H #define _SOFTFLOWD_H #include "common.h" #include "sys-tree.h" #include "freelist.h" #include "treetype.h" /* User to setuid to and directory to chroot to when we drop privs */ #ifndef PRIVDROP_USER # define PRIVDROP_USER "nobody" #endif #ifndef PRIVDROP_CHROOT_DIR # define PRIVDROP_CHROOT_DIR "/var/empty" #endif /* * Capture length for libpcap: Must fit the link layer header, plus * a maximally sized ip/ipv6 header and most of a TCP header */ #define LIBPCAP_SNAPLEN_V4 96 #define LIBPCAP_SNAPLEN_V6 160 /* * Timeouts */ #define DEFAULT_TCP_TIMEOUT 3600 #define DEFAULT_TCP_RST_TIMEOUT 120 #define DEFAULT_TCP_FIN_TIMEOUT 300 #define DEFAULT_UDP_TIMEOUT 300 #define DEFAULT_ICMP_TIMEOUT 300 #define DEFAULT_GENERAL_TIMEOUT 3600 #define DEFAULT_MAXIMUM_LIFETIME (3600*24*7) #define DEFAULT_EXPIRY_INTERVAL 60 /* * Default maximum number of flow to track simultaneously * 8192 corresponds to just under 1Mb of flow data */ #define DEFAULT_MAX_FLOWS 8192 /* Store a couple of statistics, maybe more in the future */ struct STATISTIC { double min, mean, max; }; /* Flow tracking levels */ #define TRACK_FULL 1 /* src/dst/addr/port/proto 5-tuple */ #define TRACK_IP_PROTO 2 /* src/dst/proto 3-tuple */ #define TRACK_IP_ONLY 3 /* src/dst tuple */ /* * This structure is the root of the flow tracking system. * It holds the root of the tree of active flows and the head of the * tree of expiry events. It also collects miscellaneous statistics */ struct FLOWTRACK { /* The flows and their expiry events */ FLOW_HEAD(FLOWS, FLOW) flows; /* Top of flow tree */ EXPIRY_HEAD(EXPIRIES, EXPIRY) expiries; /* Top of expiries tree */ struct freelist flow_freelist; /* Freelist for flows */ struct freelist expiry_freelist; /* Freelist for expiry events */ unsigned int num_flows; /* # of active flows */ unsigned int max_flows; /* Max # of active flows */ u_int64_t next_flow_seq; /* Next flow ID */ /* Stuff related to flow export */ struct timeval system_boot_time; /* SysUptime */ int track_level; /* See TRACK_* above */ /* Flow timeouts */ int tcp_timeout; /* Open TCP connections */ int tcp_rst_timeout; /* TCP flows after RST */ int tcp_fin_timeout; /* TCP flows after bidi FIN */ int udp_timeout; /* UDP flows */ int icmp_timeout; /* ICMP flows */ int general_timeout; /* Everything else */ int maximum_lifetime; /* Maximum life for flows */ int expiry_interval; /* Interval between expiries */ /* Statistics */ u_int64_t total_packets; /* # of good packets */ u_int64_t frag_packets; /* # of fragmented packets */ u_int64_t non_ip_packets; /* # of not-IP packets */ u_int64_t bad_packets; /* # of bad packets */ u_int64_t flows_expired; /* # expired */ u_int64_t flows_exported; /* # of flows sent */ u_int64_t flows_dropped; /* # of flows dropped */ u_int64_t flows_force_expired; /* # of flows forced out */ u_int64_t packets_sent; /* # netflow packets sent */ struct STATISTIC duration; /* Flow duration */ struct STATISTIC octets; /* Bytes (bidir) */ struct STATISTIC packets; /* Packets (bidir) */ /* Per protocol statistics */ u_int64_t flows_pp[256]; u_int64_t octets_pp[256]; u_int64_t packets_pp[256]; struct STATISTIC duration_pp[256]; /* Timeout statistics */ u_int64_t expired_general; u_int64_t expired_tcp; u_int64_t expired_tcp_rst; u_int64_t expired_tcp_fin; u_int64_t expired_udp; u_int64_t expired_icmp; u_int64_t expired_maxlife; u_int64_t expired_overbytes; u_int64_t expired_maxflows; u_int64_t expired_flush; }; /* * This structure is an entry in the tree of flows that we are * currently tracking. * * Because flows are matched _bi-directionally_, they must be stored in * a canonical format: the numerically lowest address and port number must * be stored in the first address and port array slot respectively. */ struct FLOW { /* Housekeeping */ struct EXPIRY *expiry; /* Pointer to expiry record */ FLOW_ENTRY(FLOW) trp; /* Tree pointer */ /* Flow identity (all are in network byte order) */ int af; /* Address family of flow */ u_int32_t ip6_flowlabel[2]; /* IPv6 Flowlabel */ union { struct in_addr v4; struct in6_addr v6; } addr[2]; /* Endpoint addresses */ u_int16_t port[2]; /* Endpoint ports */ u_int8_t tcp_flags[2]; /* Cumulative OR of flags */ u_int8_t protocol; /* Protocol */ /* Per-flow statistics (all in _host_ byte order) */ u_int64_t flow_seq; /* Flow ID */ struct timeval flow_start; /* Time of creation */ struct timeval flow_last; /* Time of last traffic */ /* Per-endpoint statistics (all in _host_ byte order) */ u_int32_t octets[2]; /* Octets so far */ u_int32_t packets[2]; /* Packets so far */ }; /* * This is an entry in the tree of expiry events. The tree is used to * avoid traversion the whole tree of active flows looking for ones to * expire. "expires_at" is the time at which the flow should be discarded, * or zero if it is scheduled for immediate disposal. * * When a flow which hasn't been scheduled for immediate expiry registers * traffic, it is deleted from its current position in the tree and * re-inserted (subject to its updated timeout). * * Expiry scans operate by starting at the head of the tree and expiring * each entry with expires_at < now * */ struct EXPIRY { EXPIRY_ENTRY(EXPIRY) trp; /* Tree pointer */ struct FLOW *flow; /* pointer to flow */ u_int32_t expires_at; /* time_t */ enum { R_GENERAL, R_TCP, R_TCP_RST, R_TCP_FIN, R_UDP, R_ICMP, R_MAXLIFE, R_OVERBYTES, R_OVERFLOWS, R_FLUSH } reason; }; /* Prototype for functions shared from softflowd.c */ u_int32_t timeval_sub_ms(const struct timeval *t1, const struct timeval *t2); /* Prototypes for functions to send NetFlow packets, from netflow*.c */ int send_netflow_v1(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); int send_netflow_v5(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); int send_netflow_v9(struct FLOW **flows, int num_flows, int nfsock, u_int16_t ifidx, u_int64_t *flows_exported, struct timeval *system_boot_time, int verbose_flag); /* Force a resend of the flow template */ void netflow9_resend_template(void); #endif /* _SOFTFLOWD_H */
08beeumerk-flow
softflowd.h
C
bsd
7,777
/* * Copyright (c) 2001 Kevin Steves. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" #include "convtime.h" RCSID("$Id$"); #define SECONDS 1 #define MINUTES (SECONDS * 60) #define HOURS (MINUTES * 60) #define DAYS (HOURS * 24) #define WEEKS (DAYS * 7) long int convtime(const char *s) { long total, secs; const char *p; char *endp; errno = 0; total = 0; p = s; if (p == NULL || *p == '\0') return -1; while (*p) { secs = strtol(p, &endp, 10); if (p == endp || (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) || secs < 0) return -1; switch (*endp++) { case '\0': endp--; case 's': case 'S': break; case 'm': case 'M': secs *= MINUTES; break; case 'h': case 'H': secs *= HOURS; break; case 'd': case 'D': secs *= DAYS; break; case 'w': case 'W': secs *= WEEKS; break; default: return -1; } total += secs; if (total < 0) return -1; p = endp; } return total; }
08beeumerk-flow
convtime.c
C
bsd
2,233
/* $OpenBSD: tree.h,v 1.9 2004/11/24 18:10:42 tdeval Exp $ */ /* * Copyright 2002 Niels Provos <provos@citi.umich.edu> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SYS_TREE_H_ #define _SYS_TREE_H_ /* * This file defines data structures for different types of trees: * splay trees and red-black trees. * * A splay tree is a self-organizing data structure. Every operation * on the tree causes a splay to happen. The splay moves the requested * node to the root of the tree and partly rebalances it. * * This has the benefit that request locality causes faster lookups as * the requested nodes move to the top of the tree. On the other hand, * every lookup causes memory writes. * * The Balance Theorem bounds the total access time for m operations * and n inserts on an initially empty tree as O((m + n)lg n). The * amortized cost for a sequence of m accesses to a splay tree is O(lg n); * * A red-black tree is a binary search tree with the node color as an * extra attribute. It fulfills a set of conditions: * - every search path from the root to a leaf consists of the * same number of black nodes, * - each red node (except for the root) has a black parent, * - each leaf node is black. * * Every operation on a red-black tree is bounded as O(lg n). * The maximum height of a red-black tree is 2lg (n+1). */ #define SPLAY_HEAD(name, type) \ struct name { \ struct type *sph_root; /* root of the tree */ \ } #define SPLAY_INITIALIZER(root) \ { NULL } #define SPLAY_INIT(root) do { \ (root)->sph_root = NULL; \ } while (0) #define SPLAY_ENTRY(type) \ struct { \ struct type *spe_left; /* left element */ \ struct type *spe_right; /* right element */ \ } #define SPLAY_LEFT(elm, field) (elm)->field.spe_left #define SPLAY_RIGHT(elm, field) (elm)->field.spe_right #define SPLAY_ROOT(head) (head)->sph_root #define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL) /* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */ #define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ (head)->sph_root = tmp; \ } while (0) #define SPLAY_ROTATE_LEFT(head, tmp, field) do { \ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ SPLAY_LEFT(tmp, field) = (head)->sph_root; \ (head)->sph_root = tmp; \ } while (0) #define SPLAY_LINKLEFT(head, tmp, field) do { \ SPLAY_LEFT(tmp, field) = (head)->sph_root; \ tmp = (head)->sph_root; \ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ } while (0) #define SPLAY_LINKRIGHT(head, tmp, field) do { \ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ tmp = (head)->sph_root; \ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ } while (0) #define SPLAY_ASSEMBLE(head, node, left, right, field) do { \ SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \ SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \ } while (0) /* Generates prototypes and inline functions */ #define SPLAY_PROTOTYPE(name, type, field, cmp) \ void name##_SPLAY(struct name *, struct type *); \ void name##_SPLAY_MINMAX(struct name *, int); \ struct type *name##_SPLAY_INSERT(struct name *, struct type *); \ struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \ \ /* Finds the node with the same key as elm */ \ static __inline struct type * \ name##_SPLAY_FIND(struct name *head, struct type *elm) \ { \ if (SPLAY_EMPTY(head)) \ return(NULL); \ name##_SPLAY(head, elm); \ if ((cmp)(elm, (head)->sph_root) == 0) \ return (head->sph_root); \ return (NULL); \ } \ \ static __inline struct type * \ name##_SPLAY_NEXT(struct name *head, struct type *elm) \ { \ name##_SPLAY(head, elm); \ if (SPLAY_RIGHT(elm, field) != NULL) { \ elm = SPLAY_RIGHT(elm, field); \ while (SPLAY_LEFT(elm, field) != NULL) { \ elm = SPLAY_LEFT(elm, field); \ } \ } else \ elm = NULL; \ return (elm); \ } \ \ static __inline struct type * \ name##_SPLAY_MIN_MAX(struct name *head, int val) \ { \ name##_SPLAY_MINMAX(head, val); \ return (SPLAY_ROOT(head)); \ } /* Main splay operation. * Moves node close to the key of elm to top */ #define SPLAY_GENERATE(name, type, field, cmp) \ struct type * \ name##_SPLAY_INSERT(struct name *head, struct type *elm) \ { \ if (SPLAY_EMPTY(head)) { \ SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \ } else { \ int __comp; \ name##_SPLAY(head, elm); \ __comp = (cmp)(elm, (head)->sph_root); \ if(__comp < 0) { \ SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\ SPLAY_RIGHT(elm, field) = (head)->sph_root; \ SPLAY_LEFT((head)->sph_root, field) = NULL; \ } else if (__comp > 0) { \ SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\ SPLAY_LEFT(elm, field) = (head)->sph_root; \ SPLAY_RIGHT((head)->sph_root, field) = NULL; \ } else \ return ((head)->sph_root); \ } \ (head)->sph_root = (elm); \ return (NULL); \ } \ \ struct type * \ name##_SPLAY_REMOVE(struct name *head, struct type *elm) \ { \ struct type *__tmp; \ if (SPLAY_EMPTY(head)) \ return (NULL); \ name##_SPLAY(head, elm); \ if ((cmp)(elm, (head)->sph_root) == 0) { \ if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\ } else { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\ name##_SPLAY(head, elm); \ SPLAY_RIGHT((head)->sph_root, field) = __tmp; \ } \ return (elm); \ } \ return (NULL); \ } \ \ void \ name##_SPLAY(struct name *head, struct type *elm) \ { \ struct type __node, *__left, *__right, *__tmp; \ int __comp; \ \ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ __left = __right = &__node; \ \ while ((__comp = (cmp)(elm, (head)->sph_root))) { \ if (__comp < 0) { \ __tmp = SPLAY_LEFT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if ((cmp)(elm, __tmp) < 0){ \ SPLAY_ROTATE_RIGHT(head, __tmp, field); \ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKLEFT(head, __right, field); \ } else if (__comp > 0) { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if ((cmp)(elm, __tmp) > 0){ \ SPLAY_ROTATE_LEFT(head, __tmp, field); \ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKRIGHT(head, __left, field); \ } \ } \ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ } \ \ /* Splay with either the minimum or the maximum element \ * Used to find minimum or maximum element in tree. \ */ \ void name##_SPLAY_MINMAX(struct name *head, int __comp) \ { \ struct type __node, *__left, *__right, *__tmp; \ \ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ __left = __right = &__node; \ \ while (1) { \ if (__comp < 0) { \ __tmp = SPLAY_LEFT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if (__comp < 0){ \ SPLAY_ROTATE_RIGHT(head, __tmp, field); \ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKLEFT(head, __right, field); \ } else if (__comp > 0) { \ __tmp = SPLAY_RIGHT((head)->sph_root, field); \ if (__tmp == NULL) \ break; \ if (__comp > 0) { \ SPLAY_ROTATE_LEFT(head, __tmp, field); \ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ break; \ } \ SPLAY_LINKRIGHT(head, __left, field); \ } \ } \ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ } #define SPLAY_NEGINF -1 #define SPLAY_INF 1 #define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y) #define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y) #define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y) #define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y) #define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \ : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) #define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \ : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) #define SPLAY_FOREACH(x, name, head) \ for ((x) = SPLAY_MIN(name, head); \ (x) != NULL; \ (x) = SPLAY_NEXT(name, head, x)) /* Macros that define a red-black tree */ #define RB_HEAD(name, type) \ struct name { \ struct type *rbh_root; /* root of the tree */ \ } #define RB_INITIALIZER(root) \ { NULL } #define RB_INIT(root) do { \ (root)->rbh_root = NULL; \ } while (0) #define RB_BLACK 0 #define RB_RED 1 #define RB_ENTRY(type) \ struct { \ struct type *rbe_left; /* left element */ \ struct type *rbe_right; /* right element */ \ struct type *rbe_parent; /* parent element */ \ int rbe_color; /* node color */ \ } #define RB_LEFT(elm, field) (elm)->field.rbe_left #define RB_RIGHT(elm, field) (elm)->field.rbe_right #define RB_PARENT(elm, field) (elm)->field.rbe_parent #define RB_COLOR(elm, field) (elm)->field.rbe_color #define RB_ROOT(head) (head)->rbh_root #define RB_EMPTY(head) (RB_ROOT(head) == NULL) #define RB_SET(elm, parent, field) do { \ RB_PARENT(elm, field) = parent; \ RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \ RB_COLOR(elm, field) = RB_RED; \ } while (0) #define RB_SET_BLACKRED(black, red, field) do { \ RB_COLOR(black, field) = RB_BLACK; \ RB_COLOR(red, field) = RB_RED; \ } while (0) #ifndef RB_AUGMENT #define RB_AUGMENT(x) #endif #define RB_ROTATE_LEFT(head, elm, tmp, field) do { \ (tmp) = RB_RIGHT(elm, field); \ if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) { \ RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \ } \ RB_AUGMENT(elm); \ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ else \ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ } else \ (head)->rbh_root = (tmp); \ RB_LEFT(tmp, field) = (elm); \ RB_PARENT(elm, field) = (tmp); \ RB_AUGMENT(tmp); \ if ((RB_PARENT(tmp, field))) \ RB_AUGMENT(RB_PARENT(tmp, field)); \ } while (0) #define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \ (tmp) = RB_LEFT(elm, field); \ if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) { \ RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \ } \ RB_AUGMENT(elm); \ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ else \ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ } else \ (head)->rbh_root = (tmp); \ RB_RIGHT(tmp, field) = (elm); \ RB_PARENT(elm, field) = (tmp); \ RB_AUGMENT(tmp); \ if ((RB_PARENT(tmp, field))) \ RB_AUGMENT(RB_PARENT(tmp, field)); \ } while (0) /* Generates prototypes and inline functions */ #define RB_PROTOTYPE(name, type, field, cmp) \ void name##_RB_INSERT_COLOR(struct name *, struct type *); \ void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\ struct type *name##_RB_REMOVE(struct name *, struct type *); \ struct type *name##_RB_INSERT(struct name *, struct type *); \ struct type *name##_RB_FIND(struct name *, struct type *); \ struct type *name##_RB_NEXT(struct type *); \ struct type *name##_RB_MINMAX(struct name *, int); \ \ /* Main rb operation. * Moves node close to the key of elm to top */ #define RB_GENERATE(name, type, field, cmp) \ void \ name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \ { \ struct type *parent, *gparent, *tmp; \ while ((parent = RB_PARENT(elm, field)) && \ RB_COLOR(parent, field) == RB_RED) { \ gparent = RB_PARENT(parent, field); \ if (parent == RB_LEFT(gparent, field)) { \ tmp = RB_RIGHT(gparent, field); \ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ RB_COLOR(tmp, field) = RB_BLACK; \ RB_SET_BLACKRED(parent, gparent, field);\ elm = gparent; \ continue; \ } \ if (RB_RIGHT(parent, field) == elm) { \ RB_ROTATE_LEFT(head, parent, tmp, field);\ tmp = parent; \ parent = elm; \ elm = tmp; \ } \ RB_SET_BLACKRED(parent, gparent, field); \ RB_ROTATE_RIGHT(head, gparent, tmp, field); \ } else { \ tmp = RB_LEFT(gparent, field); \ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ RB_COLOR(tmp, field) = RB_BLACK; \ RB_SET_BLACKRED(parent, gparent, field);\ elm = gparent; \ continue; \ } \ if (RB_LEFT(parent, field) == elm) { \ RB_ROTATE_RIGHT(head, parent, tmp, field);\ tmp = parent; \ parent = elm; \ elm = tmp; \ } \ RB_SET_BLACKRED(parent, gparent, field); \ RB_ROTATE_LEFT(head, gparent, tmp, field); \ } \ } \ RB_COLOR(head->rbh_root, field) = RB_BLACK; \ } \ \ void \ name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \ { \ struct type *tmp; \ while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \ elm != RB_ROOT(head)) { \ if (RB_LEFT(parent, field) == elm) { \ tmp = RB_RIGHT(parent, field); \ if (RB_COLOR(tmp, field) == RB_RED) { \ RB_SET_BLACKRED(tmp, parent, field); \ RB_ROTATE_LEFT(head, parent, tmp, field);\ tmp = RB_RIGHT(parent, field); \ } \ if ((RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ RB_COLOR(tmp, field) = RB_RED; \ elm = parent; \ parent = RB_PARENT(elm, field); \ } else { \ if (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\ struct type *oleft; \ if ((oleft = RB_LEFT(tmp, field)))\ RB_COLOR(oleft, field) = RB_BLACK;\ RB_COLOR(tmp, field) = RB_RED; \ RB_ROTATE_RIGHT(head, tmp, oleft, field);\ tmp = RB_RIGHT(parent, field); \ } \ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ RB_COLOR(parent, field) = RB_BLACK; \ if (RB_RIGHT(tmp, field)) \ RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\ RB_ROTATE_LEFT(head, parent, tmp, field);\ elm = RB_ROOT(head); \ break; \ } \ } else { \ tmp = RB_LEFT(parent, field); \ if (RB_COLOR(tmp, field) == RB_RED) { \ RB_SET_BLACKRED(tmp, parent, field); \ RB_ROTATE_RIGHT(head, parent, tmp, field);\ tmp = RB_LEFT(parent, field); \ } \ if ((RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ (RB_RIGHT(tmp, field) == NULL || \ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ RB_COLOR(tmp, field) = RB_RED; \ elm = parent; \ parent = RB_PARENT(elm, field); \ } else { \ if (RB_LEFT(tmp, field) == NULL || \ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\ struct type *oright; \ if ((oright = RB_RIGHT(tmp, field)))\ RB_COLOR(oright, field) = RB_BLACK;\ RB_COLOR(tmp, field) = RB_RED; \ RB_ROTATE_LEFT(head, tmp, oright, field);\ tmp = RB_LEFT(parent, field); \ } \ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ RB_COLOR(parent, field) = RB_BLACK; \ if (RB_LEFT(tmp, field)) \ RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\ RB_ROTATE_RIGHT(head, parent, tmp, field);\ elm = RB_ROOT(head); \ break; \ } \ } \ } \ if (elm) \ RB_COLOR(elm, field) = RB_BLACK; \ } \ \ struct type * \ name##_RB_REMOVE(struct name *head, struct type *elm) \ { \ struct type *child, *parent, *old = elm; \ int color; \ if (RB_LEFT(elm, field) == NULL) \ child = RB_RIGHT(elm, field); \ else if (RB_RIGHT(elm, field) == NULL) \ child = RB_LEFT(elm, field); \ else { \ struct type *left; \ elm = RB_RIGHT(elm, field); \ while ((left = RB_LEFT(elm, field))) \ elm = left; \ child = RB_RIGHT(elm, field); \ parent = RB_PARENT(elm, field); \ color = RB_COLOR(elm, field); \ if (child) \ RB_PARENT(child, field) = parent; \ if (parent) { \ if (RB_LEFT(parent, field) == elm) \ RB_LEFT(parent, field) = child; \ else \ RB_RIGHT(parent, field) = child; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = child; \ if (RB_PARENT(elm, field) == old) \ parent = elm; \ (elm)->field = (old)->field; \ if (RB_PARENT(old, field)) { \ if (RB_LEFT(RB_PARENT(old, field), field) == old)\ RB_LEFT(RB_PARENT(old, field), field) = elm;\ else \ RB_RIGHT(RB_PARENT(old, field), field) = elm;\ RB_AUGMENT(RB_PARENT(old, field)); \ } else \ RB_ROOT(head) = elm; \ RB_PARENT(RB_LEFT(old, field), field) = elm; \ if (RB_RIGHT(old, field)) \ RB_PARENT(RB_RIGHT(old, field), field) = elm; \ if (parent) { \ left = parent; \ do { \ RB_AUGMENT(left); \ } while ((left = RB_PARENT(left, field))); \ } \ goto color; \ } \ parent = RB_PARENT(elm, field); \ color = RB_COLOR(elm, field); \ if (child) \ RB_PARENT(child, field) = parent; \ if (parent) { \ if (RB_LEFT(parent, field) == elm) \ RB_LEFT(parent, field) = child; \ else \ RB_RIGHT(parent, field) = child; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = child; \ color: \ if (color == RB_BLACK) \ name##_RB_REMOVE_COLOR(head, parent, child); \ return (old); \ } \ \ /* Inserts a node into the RB tree */ \ struct type * \ name##_RB_INSERT(struct name *head, struct type *elm) \ { \ struct type *tmp; \ struct type *parent = NULL; \ int comp = 0; \ tmp = RB_ROOT(head); \ while (tmp) { \ parent = tmp; \ comp = (cmp)(elm, parent); \ if (comp < 0) \ tmp = RB_LEFT(tmp, field); \ else if (comp > 0) \ tmp = RB_RIGHT(tmp, field); \ else \ return (tmp); \ } \ RB_SET(elm, parent, field); \ if (parent != NULL) { \ if (comp < 0) \ RB_LEFT(parent, field) = elm; \ else \ RB_RIGHT(parent, field) = elm; \ RB_AUGMENT(parent); \ } else \ RB_ROOT(head) = elm; \ name##_RB_INSERT_COLOR(head, elm); \ return (NULL); \ } \ \ /* Finds the node with the same key as elm */ \ struct type * \ name##_RB_FIND(struct name *head, struct type *elm) \ { \ struct type *tmp = RB_ROOT(head); \ int comp; \ while (tmp) { \ comp = cmp(elm, tmp); \ if (comp < 0) \ tmp = RB_LEFT(tmp, field); \ else if (comp > 0) \ tmp = RB_RIGHT(tmp, field); \ else \ return (tmp); \ } \ return (NULL); \ } \ \ struct type * \ name##_RB_NEXT(struct type *elm) \ { \ if (RB_RIGHT(elm, field)) { \ elm = RB_RIGHT(elm, field); \ while (RB_LEFT(elm, field)) \ elm = RB_LEFT(elm, field); \ } else { \ if (RB_PARENT(elm, field) && \ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ elm = RB_PARENT(elm, field); \ else { \ while (RB_PARENT(elm, field) && \ (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\ elm = RB_PARENT(elm, field); \ elm = RB_PARENT(elm, field); \ } \ } \ return (elm); \ } \ \ struct type * \ name##_RB_MINMAX(struct name *head, int val) \ { \ struct type *tmp = RB_ROOT(head); \ struct type *parent = NULL; \ while (tmp) { \ parent = tmp; \ if (val < 0) \ tmp = RB_LEFT(tmp, field); \ else \ tmp = RB_RIGHT(tmp, field); \ } \ return (parent); \ } #define RB_NEGINF -1 #define RB_INF 1 #define RB_INSERT(name, x, y) name##_RB_INSERT(x, y) #define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y) #define RB_FIND(name, x, y) name##_RB_FIND(x, y) #define RB_NEXT(name, x, y) name##_RB_NEXT(y) #define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF) #define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF) #define RB_FOREACH(x, name, head) \ for ((x) = RB_MIN(name, head); \ (x) != NULL; \ (x) = name##_RB_NEXT(x)) #endif /* _SYS_TREE_H_ */
08beeumerk-flow
sys-tree.h
C
bsd
22,658
#include "Encrypt.h" // if test #if 0 #define SRC_FILE_PATH "test" #define KEY_CODE "123485" #define SHOW_FILE_CMD "" #else #define SRC_FILE_PATH argv[1] #define DST_FILE_PATH argv[1] #define KEY_CODE argv[2] #define SHOW_FILE_CMD argv[3] #endif #define MY_DEBUG printf int main(int argc,char **argv) { struct st_byte_stream *src = NULL; char *src_path = NULL, *encrypt_key_str = NULL; unsigned char *key_buffer; unsigned int key_len = 0; long int file_len = 0; if (SRC_FILE_PATH) { if (KEY_CODE) { encrypt_key_str = KEY_CODE; } else { MY_DEBUG("Param Er @%d\n",__LINE__); return 0; } } else { MY_DEBUG("Param Er @%d\n",__LINE__); return 0; } src = encrypt_open(SRC_FILE_PATH, &src_path); if (!src) { MY_DEBUG("Init Er @%d\n",__LINE__); return 0; } MY_DEBUG("@%s%s @Key: %s\n", src->m_Ew?"Create":"Open", src->m_Type?"File:":"String:\n\t", src_path, encrypt_key_str); //MY_DEBUG("begin...\n"); key_len = STRLEN(KEY_CODE); key_buffer = MALLOC(key_len+1); if (NULL == key_buffer) { MY_DEBUG("Malloc Er @%d\n",__LINE__); encrypt_close(&src); return 0; } MEMCPY(key_buffer,encrypt_key_str,key_len); FILE_SEEK_END(src,0); file_len = FILE_TELL(src); FILE_SEEK_SET(src, 0); encrypt_stream(src, src, file_len, key_buffer, key_len); encrypt_close(&src); //MY_DEBUG("\nOk\n"); FREE(key_buffer); key_buffer = NULL; if (SHOW_FILE_CMD) { char cmdbuffer[256]; MY_DEBUG("\nShow %s:\n",src_path); sprintf(cmdbuffer,"%s %s",SHOW_FILE_CMD,src_path); system(cmdbuffer); //MY_DEBUG("^_^\n"); } return 0; }
1001-data-encrypt
app/encrypt/src/my_mian.c
C
gpl3
1,743
/* *Copyright (c) 2009,(>WangXi<) *All rights reserved. *File Name:XXByteStrm.h/XXByteStrm.c *Description:This file define a SimClass for ByteStream Operation *version:1.0 *Author:chaoswizard@163.com(>WX<) *Create Date:Dec.14th.2009 */ #ifndef __XBYTESTRM_H__ #define __XBYTESTRM_H__ #include "XXtypeDef.h" #include <stdio.h> #define STRM_BUF_S 0x0 /*Static Alloc Array b000*/ #define STRM_BUF_D 0x4/*Dynamic Alloc Array b100*/ #define STRM_FILE_R 0x5/*Read existed File and Append b101*/ #define STRM_FILE_W 0x7/*Create new File and Append b111*/ struct st_byte_stream {// union { BYTE *Array; FILE *fp; }handle; BYTE m_Type:1;// 1 is file, 0 isArray BYTE m_Ew:1;// 1 is create new,0 is use existed BYTE m_Einc:1;// 1 is Append More,0 is can not //-------member variable----------- DWORD m_Size; long m_Position; //current position FILE *dumpFile; //-------member interface----------- void (*ShowAttri)(struct st_byte_stream *,int line); DWORD (*GetSize)(struct st_byte_stream *); long (*Tell)(struct st_byte_stream *); BOOL (*Eof)(struct st_byte_stream *); void (*Seek)(struct st_byte_stream *,long offset, int origin); int (*ReadByte)(struct st_byte_stream *); int (*Read)(struct st_byte_stream *,void *buffer, int size, int count); BOOL (*PutC)(struct st_byte_stream *stream,int c); int (*Write)(struct st_byte_stream *,const void *buffer, int size, int count); void (*Close)(struct st_byte_stream **,BOOL destoryHandle); void (*Dump)(struct st_byte_stream *,int length); void (*InitDumpFile)(struct st_byte_stream *,BYTE * name); void (*CloseDumpFile)(struct st_byte_stream *); }; //////////////////////////////////////////////////////////// //create one bytestream,MUST judge the return value,0 means failed else means successful. BOOL open_bytestrm(struct st_byte_stream **stream,void *src_data_or_path,DWORD capacity, BYTE mode); //void Print_HexStrm(FILE *dumpFile,BYTE *SrcData,int length); ////////////////////////////////////////////////////////// #endif
1001-data-encrypt
app/encrypt/src/XXByteStrm.h
C
gpl3
2,105
#ifndef __XTYPEDEF_H__ #define __XTYPEDEF_H__ typedef unsigned char BYTE;//8 bit typedef unsigned short WORD;//16 bit typedef unsigned long DWORD;//32 bit typedef unsigned int UINT; typedef DWORD COLORREF; typedef unsigned int HANDLE; typedef void* HRGN; #ifndef BOOL #define BOOL UINT #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef NULL #define NULL (void *)0 #endif #endif
1001-data-encrypt
app/encrypt/src/XXtypeDef.h
C
gpl3
484
#ifndef __MACRO_PUB_DEFINE_H__ #define __MACRO_PUB_DEFINE_H__ #include "malloc.h" #define MALLOC(size) malloc(size) #define FREE(ptr) free(ptr) //========================================================== #include "XXByteStrm.h" #define FILE_READ(fp, buffer, len) ((fp)->Read(fp, buffer , 1, len)) #define FILE_WRITE(fp, buffer, len) ((fp)->Write(fp, buffer, 1, len)) #define FILE_SEEK_SET(fp, pos) ((fp)->Seek(fp, pos, SEEK_SET)) #define FILE_SEEK_END(fp, pos) ((fp)->Seek(fp, pos, SEEK_END)) #define FILE_TELL(fp) ((fp)->Tell(fp)) #define FILE_CLOSE(fp) ((fp)->Close(&(fp), TRUE)) #include "string.h" #define STRLEN(str) strlen(str) #define MEMCPY(d, s, l) memcpy(d, s, l) #endif
1001-data-encrypt
app/encrypt/src/macro_pub_define.h
C
gpl3
814
#ifndef __MYENCRYPT_H__ #define __MYENCRYPT_H__ #include "macro_pub_define.h" struct st_byte_stream *encrypt_open(const char *path, char **real_path); int encrypt_close(struct st_byte_stream **src_stream); int encrypt_stream(struct st_byte_stream *dest, struct st_byte_stream *src, long int len, const char *key_data, int key_len); #endif
1001-data-encrypt
app/encrypt/src/Encrypt.h
C
gpl3
405
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; } }
101j
P6Extensions/src/insight/web/delegates/ReflectionDelegate.java
Java
gpl3
1,224
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); } }
101j
P6Extensions/src/insight/web/delegates/AjaxJSONDelegate.java
Java
gpl3
2,505
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(); } }
101j
P6Extensions/src/insight/web/delegates/PrimaveraDelegate.java
Java
gpl3
38,494
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; } } }
101j
P6Extensions/src/insight/web/controllers/ProjectCodeController.java
Java
gpl3
3,537
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); } }
101j
P6Extensions/src/insight/web/controllers/AddOpportunityController.java
Java
gpl3
24,643
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; } }
101j
P6Extensions/src/insight/web/controllers/WorkflowController.java
Java
gpl3
10,799
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; } }
101j
P6Extensions/src/insight/web/controllers/GenericController.java
Java
gpl3
1,243
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; } }
101j
P6Extensions/src/insight/web/controllers/PrimaveraActionsController.java
Java
gpl3
4,702
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 + "]"; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Roles.java
Java
gpl3
2,047
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); } }
101j
P6Extensions/src/insight/miescor/opp/domain/PRCInput.java
Java
gpl3
1,484
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/CodeValue.java
Java
gpl3
445
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 }
101j
P6Extensions/src/insight/miescor/opp/domain/Review.java
Java
gpl3
10,457
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); } }
101j
P6Extensions/src/insight/miescor/opp/domain/Customer.java
Java
gpl3
1,295
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/WorkflowMaster.java
Java
gpl3
386
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Opportunity.java
Java
gpl3
14,951
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/OppReport.java
Java
gpl3
3,737
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 + "]"; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Activity.java
Java
gpl3
1,597
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/NumberGenerator.java
Java
gpl3
1,215
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 + "]"; } }
101j
P6Extensions/src/insight/miescor/opp/domain/WorkflowRole.java
Java
gpl3
1,898
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 + "]"; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Workflow.java
Java
gpl3
2,527
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); } } }
101j
P6Extensions/src/insight/miescor/opp/domain/ILocation.java
Java
gpl3
1,346
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/ICurrency.java
Java
gpl3
1,210
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/AssignmentGrid.java
Java
gpl3
1,659
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 + "]"; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Assignment.java
Java
gpl3
5,413
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; } }
101j
P6Extensions/src/insight/miescor/opp/domain/Users.java
Java
gpl3
832
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"; } }
101j
P6Extensions/src/insight/miescor/annotations/Constants.java
Java
gpl3
3,789
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; }
101j
P6Extensions/src/insight/miescor/annotations/Notebook.java
Java
gpl3
361
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(); }
101j
P6Extensions/src/insight/miescor/annotations/UDF.java
Java
gpl3
335
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(); }
101j
P6Extensions/src/insight/miescor/annotations/Code.java
Java
gpl3
321
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; } }
101j
P6Extensions/src/insight/miescor/db/DBManager.java
Java
gpl3
4,332
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; } }
101j
P6Extensions/src/insight/miescor/db/AssignmentMapper.java
Java
gpl3
1,050
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; } }
101j
P6Extensions/src/insight/p6/event/QueueReceive.java
Java
gpl3
8,756
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); } }
101j
P6Extensions/src/insight/p6/event/QueueSend.java
Java
gpl3
3,835
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; } }
101j
P6Extensions/src/insight/jsp/custom/taglib/CustomerSelTagHandler.java
Java
gpl3
1,045
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; } }
101j
P6Extensions/src/insight/jsp/custom/taglib/ButtonTagHandler.java
Java
gpl3
1,325
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; }; }
101j
P6Extensions/src/insight/jsp/custom/taglib/FormTagHandler.java
Java
gpl3
1,468
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; } }
101j
P6Extensions/src/insight/jsp/custom/taglib/LocationSelTagHandler.java
Java
gpl3
1,045
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; } }
101j
P6Extensions/src/insight/jsp/custom/taglib/PageHeaderTagHandler.java
Java
gpl3
1,320
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; } }
101j
P6Extensions/src/insight/jsp/custom/taglib/AttributeTagHandler.java
Java
gpl3
4,630
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; // } // } }
101j
P6Extensions/src/TestStub.java
Java
gpl3
10,718
<div id="locationSelDlg" class="easyui-dialog" title="Select Location..." style="width: 400px; height: 300px; padding: 10px" data-options="toolbar: '#locationSel-toolbar', buttons: '#locationSel-buttons', closed: true"> <ul id="locationSelTree" class="easyui-tree" style="width: 200px;" data-options="url:'loadLocations.htm'"></ul> </div> <div id="addNewLocationDlg" class="easyui-dialog" title="Add New Location..." style="width: 400px; height: 300px; padding: 10px" data-options="buttons: '#addLocation-buttons', closed: true"> <table> <tr> <td>Name:</td> <td><input class="easyui-validatebox" type="text" name="newLocationName" id="newLocationName" style="width: 250px;" data-options="required:true"></input></td> </tr> <tr> <td>Street</td> <td><input class="easyui-validatebox" type="text" name="newLocationStreet1" id="newLocationStreet1" style="width: 250px;"></input> </td> </tr> <tr> <td style="vetical-align:top;"></td> <td><input class="easyui-validatebox" type="text" name="newLocationStreet2" id="newLocationStreet2" style="width: 250px;"></input> </td> </tr> <tr> <td>City:</td> <td><input class="easyui-validatebox" type="text" name="newLocationCity" id="newLocationCity" style="width: 250px;"></input> </td> </tr> <tr> <td>State/Province:</td> <td><input class="easyui-validatebox" type="text" name="newLocationState" id="newLocationState" style="width: 250px;"></input> </td> </tr> <tr> <td>Postal Code:</td> <td><input class="easyui-validatebox" type="text" name="newLocationPostalCode" id="newLocationPostalCode" style="width: 250px;"></input> </td> </tr> <tr> <td>Country:</td> <td><input id="newLocationCountryList" class="easyui-combobox" style="width: 60px;" data-options="valueField:'value',textField:'text',url:'getCountryList.htm'"/> </td> </tr> </table> </div> <div id="locationSel-toolbar" style="padding: 2px 0"> <table cellpadding="0" cellspacing="0" style="width: 100%"> <tr> <td style="padding-left: 2px"><a id="addLocation" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">Add New</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-help',plain:true">Help</a></td> </tr> </table> </div> <script type="text/javascript"> function addNewLocation() { $("#locationSelDlg").dialog("close"); $("#addNewLocationDlg").dialog("open"); } function selectLocationValue() { var node = $('#locationSelTree').tree('getSelected'); if (node) { $("#location").val(node.text); $("#hidlocation").val(node.id); $('#locationSelDlg').dialog('close'); enableDisableValidation('location','hidlocation'); } } function selectLocation() { $('#locationSelDlg').dialog('open'); } function saveNewLocation() { var data = { name : $("#newLocationName").val() }; if($("#newLocationStreet1").val()!="") data["street1"]=$("#newLocationStreet1").val(); if($("#newLocationStreet2").val()!="") data["street2"]=$("#newLocationStreet2").val(); if($("#newLocationCity").val()!="") data["city"]=$("#newLocationCity").val(); if($("#newLocationState").val()!="") data["state"]=$("#newLocationState").val(); if($("#newLocationPostalCode").val()!="") data["postalCode"]=$("#newLocationPostalCode").val(); var country=$("#newLocationCountryList").combobox('getValue'); if(country!="") data["country"]=country; $.postJSON("addNewLocation.htm", data, function(result) { if (result.success) { $("#location").val(result.text); $("#hidlocation").val(result.id); $("#addNewLocationDlg").dialog("close"); enableDisableValidation('location','hidlocation'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function showMessager(title, message) { $.messager.show({ title : title, msg : message, showType : 'show' }); } /*$(document).ready(function(){ $.getJSON('getCountryList.htm',function(data){ $.each(data,function(ind,obj){ }); }); });*/ $("#addLocation").click(addNewLocation); $("#locationSel").click(selectLocation); </script> <div id="locationSel-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="selectLocationValue()">Select</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#locationSelDlg').dialog('close')">Close</a> </div> <div id="addLocation-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" id="saveNewLocationBtn" onclick="saveNewLocation();">Save</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#addNewLocationDlg').dialog('close')">Close</a> </div>
101j
P6Extensions/resources/locationsel.inc
HTML
gpl3
5,231
<input class="easyui-validatebox selector" type="text" name="{id}" id="{id}" data-options="required:true" style="width: 340px; height: 20px" readonly="true"></input> &nbsp; <a id="{id}Sel" href="javascript:void(0)" class="easyui-linkbutton" style="vertical-align: bottom"><img src="includes/images/hierarchy.png" width="16" height="16" /></a> <input type="hidden" id="hid{id}" name="hid{id}" />
101j
P6Extensions/resources/codetag.inc
HTML
gpl3
407
<script type="text/javascript" src="includes/js/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", plugins: [ "advlist autolink lists link image table anchor textcolor" ], toolbar: "undo redo | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table styleselect", menubar:false, statusbar:false }); </script>
101j
P6Extensions/resources/tinymce.inc
HTML
gpl3
489
<input class="easyui-numberbox" data-options="precision:2,groupSeparator:','" name="{id}" id="{id}" {reqStr} style="vertical-align: bottom; width: 200px;"/> <input id="{id}Cur" class="easyui-combobox" style="width: 60px;" data-options="valueField:'id',textField:'text',url:'loadCurrencies.htm', editable:false"/> <a id="{id}Sel" href="javascript:void(0)" class="easyui-linkbutton" style="vertical-align: bottom; height: 20px; width: 30px"><img src="includes/images/plus.png" /></a> <br> <select id="{id}Breakup" size="4" style="width: 268px; margin-top: 2px;margin-right:-1px;"></select> <a id="contractValClear" href="javascript:void(0)" class="easyui-linkbutton" style="vertical-align: top; height: 20px; width: 30px;margin-top:2px;"><img src="includes/images/minus.png" style="margin-top:4px;" /></a>
101j
P6Extensions/resources/costtag.inc
HTML
gpl3
855
<div id="customerSelDlg" class="easyui-dialog" title="Select Customer..." style="width: 400px; height: 300px; padding: 10px" data-options="toolbar: '#customerSel-toolbar', buttons: '#customerSel-buttons', closed: true"> <ul id="customerSelTree" class="easyui-tree"></ul> </div> <div id="addNewCustomerDlg" class="easyui-dialog" title="Add New Customer..." style="width: 400px; height: 200px; padding: 10px" data-options="buttons: '#addCustomer-buttons', closed: true"> <table> <tr> <td>Parent:</td> <td><input class="easyui-combotree" id="newParentId" style="width: 200px;"></td> </tr> <tr> <td>Customer Id:</td> <td><input class="easyui-validatebox" type="text" name="newCustomerId" id="newCustomerId" style="width: 100px;" maxlength="20" data-options="required:true"></input></td> </tr> <tr> <td>Customer Name:</td> <td><input class="easyui-validatebox" type="text" name="newCustomerName" id="newCustomerName" style="width: 250px;" data-options="required:true"></input></td> </tr> </table> </div> <div id="customerSel-toolbar" style="padding: 2px 0"> <table cellpadding="0" cellspacing="0" style="width: 100%"> <tr> <td style="padding-left: 2px"><a id="addCustomer" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">Add New</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-help',plain:true">Help</a></td> </tr> </table> </div> <script type="text/javascript"> function addNewCustomer() { $.getJSON('loadProjectCode.htm?code=Customer', function(data) { $("#customerSelDlg").dialog("close"); $("#newParentId").combotree('loadData', data); $("#addNewCustomerDlg").dialog("open"); }); } function selectValue() { var node = $('#customerSelTree').tree('getSelected'); if (node) { $("#customer").val(node.text); $("#hidcustomer").val(node.id); $('#customerSelDlg').dialog('close'); enableDisableValidation('customer','hidcustomer'); } } function selectCustomer() { $.getJSON("loadProjectCode.htm?code=Customer", function(data) { $("#customerSelTree").tree('loadData', data); }); $('#customerSelDlg').dialog('open'); } function saveNewCustomer() { var node = $("#newParentId").combotree('tree').tree('getSelected'); var parentId = node ? node.id : ""; var data = { "parentId" : parentId, "id" : $("#newCustomerId").val(), "name" : $("#newCustomerName").val() }; $.postJSON("addNewCustomer.htm", data, function(result) { if (result.success) { $("#customer").val(result.text); $("#hidcustomer").val(result.id); $("#addNewCustomerDlg").dialog("close"); enableDisableValidation('customer','hidcustomer'); } else { showMessager("Exception", result.message); } }, function(xhr, ajaxOptions, thrownError) { showMessager("Exception", thrownError); }); } function showMessager(title, message) { $.messager.show({ title : title, msg : message, showType : 'show' }); } $("#addCustomer").click(addNewCustomer); $("#customerSel").click(selectCustomer); </script> <div id="customerSel-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="selectValue()">Select</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#customerSelDlg').dialog('close')">Close</a> </div> <div id="addCustomer-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" id="saveNewCustomerBtn" onclick="saveNewCustomer();">Save</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#addNewCustomerDlg').dialog('close')">Close</a> </div>
101j
P6Extensions/resources/customersel.inc
HTML
gpl3
3,929
<meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="includes/js/jquery/themes/metro-orange/easyui.css"> <link rel="stylesheet" type="text/css" href="includes/js/jquery/themes/icon.css"> <script type="text/javascript" src="includes/js/jquery/jquery.min.js"></script> <script type="text/javascript" src="includes/js/jquery/jquery.easyui.min.js"></script> <script type="text/javascript" src="includes/js/jquery/postjson.js"></script> <script type="text/javascript" src="includes/js/jquery/global.js"></script>
101j
P6Extensions/resources/jquery.inc
HTML
gpl3
538
<%@taglib prefix="in" uri="/WEB-INF/TagDescriptor.tld"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Resource Details</title> <in:pHeader incTiny="yes" /> <link rel="stylesheet" type="text/css" href="includes/css/style.css" /> <script type="text/javascript" src="includes/js/resourceDetails.js"></script> </head> <body> <div id="winAddNotes" class="easyui-window" title="Business Development Review" style="width: 600px; height: 400px" data-options="iconCls:'icon-save',modal:true,closed:true"> </div> <in:form id="ff" style="height: 600px;" title="Resource Details"> <input type="hidden" name="userId" id="userId" value="${userId}" /> <input type="hidden" name="opportunityId" id="opportunityId" value="${opportunityId}" /> <input type="hidden" name="prjObjId" id="prjObjId" value="${prjObjId}" /> <input type="hidden" name="assignmentId" id="assignmentId" value="${assignmentId}" /> <table id="resourceGrid" style="height: 250px" singleSelect="true" fitColumns="true"> <thead> <tr> <th field="resId">Resource Id</th> <th field="resName">Resource Name</th> <th field="resType">Resource Type</th> <th field="roleName">Role Name</th> <th field="units">Units</th> </tr> </thead> </table> </in:form> </body> </html>
101j
P6Extensions/WebContent/WEB-INF/jsp/ResourceDetails.jsp
Java Server Pages
gpl3
1,457
<%@taglib prefix="in" uri="/WEB-INF/TagDescriptor.tld"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Opportunity Review</title> <in:pHeader incTiny="yes" /> <link rel="stylesheet" type="text/css" href="includes/css/style.css" /> <script type="text/javascript" src="includes/js/review.js"></script> </head> <body> <div id="winAddNotes" class="easyui-window" title="Additional Notes" style="width: 600px; height: 400px" data-options="iconCls:'icon-save',modal:true,closed:true"> <div id="addNotesContent" style="margin-left: 5px; margin-right: 5px;"></div> </div> <in:form id="ff" style="height: 600px;" title="Review Opportunity - Legal"> <input type="hidden" name="userId" id="userId" value="${userId}" /> <input type="hidden" name="opportunityId" id="opportunityId" value="${opportunityId}" /> <input type="hidden" name="prjObjId" id="prjObjId" value="${prjObjId}" /> <input type="hidden" name="assignmentId" id="assignmentId" value="${assignmentId}" /> <div class="easyui-accordion"> <div title="Details" style="overflow: auto; padding: 5px;"> <table> <in:attr title="Favourable Terms" id="favourableTerms" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Adverse Terms" id="adverseTerms" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Regulatory Requirements" id="regulatoryRequirement" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Additional Notes" id="addNotes" type="addNotes" style="height: 120px; width: 400px"></in:attr> <input type="hidden" id="hiddenAddNotes" /> </table> </div> <div title="Ratings" style="overflow: auto; padding: 5px;"> <table> <in:attr title="Regulatory Requirements" id="regulatoryRating" type="p6code" code="Regulatory Requirements" style="width:200px;" required="yes"></in:attr> <in:attr title="Risk Rating" id="riskRating" type="p6code" code="Risk Rating" style="width:200px;" required="yes"></in:attr> </table> </div> </div> <div style="text-align: right; padding: 15px"> <in:btn id="saveBtn" title="Save" onclick="saveReviewData();" /> &nbsp;&nbsp; <in:btn id="ApproveBtn" title="Approve" onclick="approveReview();" /> </div> </in:form> </body> </html>
101j
P6Extensions/WebContent/WEB-INF/jsp/LegalReview.jsp
Java Server Pages
gpl3
2,531
<%@taglib prefix="in" uri="/WEB-INF/TagDescriptor.tld"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Financial Review</title> <in:pHeader incTiny="yes" /> <link rel="stylesheet" type="text/css" href="includes/css/style.css" /> <script type="text/javascript" src="includes/js/review.js"></script> </head> <body> <div id="winAddNotes" class="easyui-window" title="Additional Notes" style="width: 600px; height: 400px" data-options="iconCls:'icon-save',modal:true,closed:true"> <div id="addNotesContent" style="margin-left: 5px; margin-right: 5px;"></div> </div> <in:form id="ff" style="height: 600px;" title="Register New Opportunity"> <input type="hidden" name="userId" id="userId" value="${userId}" /> <input type="hidden" name="opportunityId" id="opportunityId" value="${opportunityId}" /> <input type="hidden" name="prjObjId" id="prjObjId" value="${prjObjId}" /> <input type="hidden" name="assignmentId" id="assignmentId" value="${assignmentId}" /> <div class="easyui-accordion"> <div title="Details" style="overflow: auto; padding: 5px;"> <table> <!-- Table Header --> <in:attr title="Contract Value(PHP)<br>(excluding taxes)" id="contractValue" type="number"></in:attr> <in:attr title="Realization" id="realization" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Risk Assessment" id="finRiskAssessment" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Financial Viability" id="finViability" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Funding Details" id="fundingDetail" type="textarea" style="height: 120px; width: 400px"></in:attr> <in:attr title="Additional Notes" id="addNotes" type="addNotes" style="height: 120px; width: 400px"></in:attr> <input type="hidden" id="hiddenAddNotes" /> </table> </div> <div title="Ratings" style="overflow: auto; padding: 5px;"> <table> <in:attr title="Contract Value" id="contractValueRating" type="p6code" code="Contract Value" style="width:200px;" required="yes"></in:attr> <in:attr title="Financial Viability" id="finViabilityRating" type="p6code" code="Financial Viability" style="width:200px;" required="yes"></in:attr> <in:attr title="Realization" id="realizationRating" type="p6code" code="Realization" style="width:200px;" required="yes"></in:attr> <in:attr title="Project Funding" id="projectFunding" type="p6code" code="Project Funding" style="width:200px;" required="yes"></in:attr> <in:attr title="Risk Rating" id="riskRating" type="p6code" code="Risk Rating" style="width:200px;" required="yes"></in:attr> </table> </div> </div> <div style="text-align: right; padding: 15px"> <in:btn id="saveBtn" title="Save" onclick="saveReviewData();" /> &nbsp;&nbsp; <in:btn id="ApproveBtn" title="Approve" onclick="approveReview();" /> </div> </in:form> </body> </html>
101j
P6Extensions/WebContent/WEB-INF/jsp/FinancialReview.jsp
Java Server Pages
gpl3
3,232
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="includes/css/pivot.css"> <script type="text/javascript" src="includes/js/jquery/d3.v3.min.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="includes/js/jquery/jquery.min.js"></script> <script type="text/javascript" src="includes/js/jquery/jquery-ui-1.9.2.custom.min.js"></script> <script type="text/javascript" src="includes/js/jquery/pivot.js"></script> <script type="text/javascript" src="includes/js/jquery/gchart_renderers.js"></script> <script type="text/javascript" src="includes/js/jquery/d3_renderers.js"></script> <!-- <script type="text/javascript" src="jquery.ui.touch-punch.min.js"></script> --> </head> <body> <script type="text/javascript"> google.load("visualization", "1", { packages : [ "corechart", "charteditor" ] }); $(function() { var derivers = $.pivotUtilities.derivers; $.getJSON("includes/js/data.json", function(mps) { $("#output").pivotUI( mps, { renderers : $.extend($.pivotUtilities.renderers, $.pivotUtilities.gchart_renderers, $.pivotUtilities.d3_renderers), derivedAttributes : { "Age Bin" : derivers.bin("Age", 10), "Gender Imbalance" : function(mp) { return mp["Gender"] == "Male" ? 1 : -1; } }, cols : [ "Age Bin" ], rows : [ "Gender" ], rendererName : "Area Chart" }); }); }); </script> <div id="output" style="margin: 30px;"></div> </body> </html>
101j
P6Extensions/WebContent/WEB-INF/jsp/pivotChart.jsp
Java Server Pages
gpl3
1,930